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

$array=array("1st"=>"My House","2nd"=>"My Car","3rd"=>"My Lab");

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

// get all the array keys$arrayKeys=array_keys($array);// get amount of values from array$count=count($array);// loop through the keysfor($i=0;$i<$count;$i++){// get each array value using its keyecho$array[($arrayKeys[$i])]."<br />";}

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:

$firstKey=$arrayKeys[0];// which is '1st'$firstValue=$array[$firstKey];// which is 'My House' ($array('1st'))

The foreach structure does all the groundwork for you:

foreach($arrayas$someVar){echo$someVar."<br />";}

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

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. Example: