PHP foreach loops

The FOR loop from the last page is fine if you know how many items of data are held in the array. Sometimes you will not know so you can use FOREACH instead. FOREACH runs through an array until the end and then stops. Very useful.

Basics

Open arraysandloops.php and add this loop after the existing FOR loop:

echo "<p>The four names were";
foreach ($names as $name) {
    echo " $name";
}
echo ".</p>";                        
        

The new bit is the use of AS. The FOREACH line basically says "Get each element in the array and put it in a variable called $name". Each time the new line will write over anything which was in the variable $name from the last time through the loop.

Save, upload and run and the results should be identical to the FOR loop. The loop grabs each array element in turn saving it in the variable $name. The loops ends when no data is left

Now add a new name to the four already in arraysandloops.php (if you changed it to an assocaitive array you might want to change it back):

$names[4]="Pete";            
        

Save, upload and view and the two loops should have different results. The FOR loop still stops after four names. The FOREACH continues to the end of the array.

FOREACH loops are especially helpful when dealing with lists of data of unknown length. These are often extracted from files, databases or forms with unknown numbers of entries.

Making use of the keys as well as values

An array will contain a key to uniquely identify the data in each row. For example, the key for Pete is 4. To extract the key as well as the value from the array do this:

echo "<p>The names were ";
foreach ($names as $key=>$name) {
    echo "Name $key was $name ";
}
echo ".</p>";
        

Try this code. Then adapt it by making the array an associative array again. The key will now be a word rather than a number which could be useful. Change the ECHO inside the loop to something like:

echo "<p>The members of The Beatles were:</p>";
foreach ($names as $key=>$name) {
    echo "<p>$name (playing $key)</p>";
}
        

Play with that for a while with different types of data.

submit to reddit Delicious Tweet