Arrays and PHP For Each Loops

 

In the previous section, you saw what a Associative array was, and that they use text as the Key. In this lesson, you'll learn how to access each element in Associative array - with the For Each loop. So study the following code (try it out in a script):

$full_name = array( );

$full_name["David"] = "Gilmour";
$full_name["Nick"] = "Mason";
$full_name["Roger"] = "Waters";
$full_name["Richard"] = "Wright";

foreach ($full_name as $key_name => $key_value) {

print "Key = " . $key_name . " Value = " . $key_value . "<BR>";

}

The For Each loop is a little more complex than other loops you've met. In the script above, we set up the array as normal. But the first line of the loop is this:

foreach ($full_name as $key_name => $key_value) {

Notice that the name of the loop is one word: foreach and NOT for each. Next comes the round brackets. Inside of the round brackets, we have this:

$full_name as $key_name => $key_value

You start by typing the name of the array you want to loop round. For us, that was $full_name. Next is this:

as $key_name => $key_value

This means, "Get the Key and its Value from the array called $full_name. The Key is called $key_name in the script above, and the value is called $key_value. But these are just variable names. You can call them almost anything you like. Would could have had this:

foreach ($full_name as $first_name => $surname) {

When you use foreach, PHP knows that it's accessing the key name first and then the key value. It knows this because of the => symbol between the two. It then returns the values into your variable names, whatever they may be.

Once your loop code is executed (a print statement for us), it then loops round and returns the next Key/Value pair, storing the results in your variables.

If you need to access values from an Associative array, then, use a foreach loop.

In the next few sections, you'll see some useful things you can do with arrays.