foreach loop

The Code

foreach ($array as $someVar) {
echo ($someVar . "<br />");


Foreach loops are a special form of the standard for loop. The example above will print the value of each cell in $array. The foreach loop allows you easily work through all the items in a collection (like an array).


foreach with non-integer keys

Foreach loops are particularly useful when dealing with an array with keys that are not numbers. Consider this example:

$array = array("1st"=>"My House","2nd"=>"My Car","3rd"=>"My Lab");
$arrayKeys = array_keys($array);
for ($i=0;$i<count($array);$i++) {
echo $array[($arrayKeys[$i])] . "<br />";


Basically, if you want to go through the array with integers, you have to make a new array with the keys and then use that array to assign the key which quickly gets complicated.

The first time the for loop runs, you have (note: this is not output, just a diagram to help you see what is going on):


which is equal to
which is equal to
"My House"

Using the foreach is much better.

$array = array("1st"=>"My House","2nd"=>"My Car","3rd"=>"My Lab");
foreach ($array as $someVar) {
echo $someVar . "\n";


See how easy that was? The Output:

My House
My Car
My Lab


foreach with key assignment and output

In some cases that $i (in other words, the key for that array element) is very useful for other things! Well, in that case, use this form of foreach:

foreach ($array as $key => $value)


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.


$array = array("1st"=>"My House","2nd"=>"My Car","3rd"=>"My Lab");
foreach ($array as $i => $someVar) {
echo $i . ": " . $someVar . "<br />\n";

This will output:

1st: My House<br />
2nd: My Car<br />
3rd: My Lab<br />


Note that if you change the assigned variable inside the foreach 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.


$array = array("1st"=>"My House","2nd"=>"My Car","3rd"=>"My Lab");
foreach ($array as $i => $someVar) {
if($someVar=="My Lab")
$array[$i]="My Laboratory";



All text is available under the terms of the GNU Free Documentation License
Source : Wikibooks