PHP Programming/The foreach Loop

The code
or

Analysis
The foreach loop is a special form of the standard for loop. The example above will print all the values of $array. The foreach structure is a convenient way to loop through an array.

Simple foreach statement
Foreach loops are useful when dealing with an array indexed with arbitrary keys (e.g. non-numeric ones):

To use the classical for structure, you'd have to write:

Basically, an array value can be accessed only from its key: to make sure you get all the values, you first have to make a list of all the existings keys, then grab all the corresponding values. The access to first array value, the previous example does the following steps:

The foreach structure does all the groundwork for you:

Note how the latter example is easier to read (and write). Both will output: My House My Car My Lab

foreach with key values
If you need to use the array's keys in the body of your loop, just add the variable as in the following statement. The phrase '$myKey => $value' makes the value of the key accessible:

Note that this is very useful when constructing a dropdown list in HTML. You can use a foreach-loop to have the $myKey variable inserted into the <tt>value="..."</tt> part and the <tt>$value</tt> as the actual text.

This form mimics the way we used custom keys for $array elements. It will not only assign the elements of $array to $someVar, but also assign the keys of those elements to $i.

Note that, if you change the assigned variable inside the <tt>foreach</tt> loop, the change will not be reflected to the array. Therefore, if you need to change elements of the array you need to change them by using the array key. Example: