Saturday, August 16, 2008

PHP foreach loop tutorial - Foreach for associative arrays

The foreach loop is a bit special control structure. Foreach was designed to iterate over an array and you can use it only for array variables.
The syntax is the following:

foreach (array_expression as $value) statement

It means that the foreach loop iterates over an array and in each iteration it copies the actual array value to the $value variable. You can so use it in your statement. A real example looks like this:

Code:

  1. $test = array(1,2,3,4,5,6,7,8,9,10);

  2.  

  3. foreach ($test as $value) {

  4. echo "$value - ";

  5. }

PHP F1



The $value is a new variable so if you change it's value then the value in the array will not be changed. If you want to to this you need to use reference variables as follows:



Code:

  1. // Creat the test array

  2. $test = array(1,2,3,4,5,6,7,8,9,10);

  3.  

  4. // Modify the array content as we use reference variable

  5. foreach ($test as &$value) {

  6. $value = $value*2;

  7. }

  8.  

  9. // Display the array

  10. foreach ($test as &$value) {

  11. echo "$value - ";

  12. }

PHP F1



In the next step you will see how to display an associative array with foreach.



Sometimes it would be usefull to display not only the array values but the keys as well. In this case you don't have to choose an other looping statement. There is a much better way. The foreach statement has an addition syntax as well designed to solve this problem.

The syntax is:



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

As you can see here not only a $value variable is present in the foreach header but a $key as well. And yes it contains the actual key. So you can use this to display your associative array with foreach like this:

Code:

  1. $test = array('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);

  2.  

  3. foreach ($test as $key => $value) {

  4. echo "$key - $value <br/>" ;

  5. }

  6.  

PHP F1

No comments: