Looping Over Arrays


You already know you can loop over an array using a for loop and the count function, which determines how many elements an array contains:

 <?php     $fruits[0] = "pineapple";     $fruits[1] = "pomegranate";     $fruits[2] = "tangerine";     for ($index = 0; $index < count($fruits); $index++){         echo $fruits[$index], "\n";     } ?> 

Here's what you get:

 pineapple pomegranate tangerine 

There's also a function for easily displaying the contents of an array, print_r:

 <?php     $fruits[0] = "pineapple";     $fruits[1] = "pomegranate";     $fruits[2] = "tangerine";     print_r($fruits); ?> 

Here are the results:

 Array (     [0] => pineapple     [1] => pomegranate     [2] => tangerine ) 

The foreach statement was specially created to loop over collections such as arrays. This statement has two forms:

 foreach (array_expression as $value) statement foreach (array_expression as $key => $value) statement 

The first form of this statement assigns a new element from the array to $value each time through the loop. The second form places the current element's key, another name for its index, in $key and its value in $value each time through the loop. For example, here's how you can display all the elements in an array using foreach:

 <?php     $fruits = array("pineapple", "pomegranate", "tangerine");     foreach ($fruits as $value) {         echo "Value: $value\n";     } ?> 

Here are the results:

 Value: pineapple Value: pomegranate Value: tangerine 

And here's how you can display both the keys and values of an array:

 <?php     $fruits = array("pineapple", "pomegranate", "tangerine");     foreach ($fruits as $key => $value) {         echo "Key: $key; Value: $value\n";     } ?> 

Here are the results:

 Key: 0; Value: pineapple Key: 1; Value: pomegranate Key: 2; Value: tangerine 

You can even use a while loop to loop over an array if you use a new function, each. The each function is meant to be used in loops over collections such as arrays; each time through the array, it returns the current element's key and value and then moves to the next element. To handle a multiple-item return value from an array, you can use the list function, which will assign the two return values from each to separate variables.

Here's what this looks like for our $fruits array:

 <?php     $fruits = array("pineapple", "pomegranate", "tangerine");     while (list($key, $value) = each ($fruits)) {         echo "Key: $key; Value: $value\n";     } ?> 

Here's what you get from this script:

 Key: 0; Value: pineapple Key: 1; Value: pomegranate Key: 2; Value: tangerine 



    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net