Last Updated:

PHP iteration of the array

The standard function for php is iterating through the array. The array in the problem is associative. In general, the standard task is to find elements in an array by brute force. The trick is that when bypassing the next level of the array, set the "human name to the key" - in the example, the nesting is higher than two, but it seems to me that this one is enough to understand the essence.

Task.

 

During the execution of the code, an array is formed with data that obviously comes from the database either about customers or about users of the site. Check out the code below:

You can see the last element of the array differing from [0] and [1] in that it does not contain the element [id]. You need to add similar ones to it if they meet this element and assign it a random value from 18 to 55.

Decision.

The arrays are nested within each other to make a sequential iteration of the associative arrays. In php, this is done by the foreach function, more about it on the php.net. The keys $key 1 and $key 2 are set so as not to get confused - the larger the number, the deeper the search occurs. On line 4, the [id] array is checked, if it is missing- the next line assigns a random value.