Pages

Monday, September 06, 2010

Magical foreach loop

The foreach loop takes an array and loops through each element in the array without the need for a test condition or loop counter. As it steps through each element in the array it temporarily stores the value of that element in a variable.


This loop is useful for the array which is consist of unknown number of element. It iterates until the end of the array. The loop has two formats,


First

Foreach(($ArrayName As $ArrayItem)
{
Execute the contents of these braces;
}


This means that for each item in the array, it will iterate around the loop. “$ArrayName” is the name of the array. We can take any name for the “$ArrayItem” variable. If we echo $ArrayItem variable, we will get the values of the array named “ArrayName”.



Second

Foreach($ArrayName As $ArrayIndexValue=>$ArrayItem)
{
Execute the contents of these braces
}


This is the same as the first format, but it makes the array index value available as well. The first argument is the array name. The second and third arguments are variable names that we create our self to hold the index value and the corresponding element in the array.


There might also be missing entries in the array, but it doesn’t have to check every index value, only the elements that contain values. Assume, we have an array named “$states_of_the_USA” , which has 50 elements . We could include the following code, which adds a new element to the array of states:

$states_of_the_USA[100]=”Atlantis”;

Then if we performed the foreach loop, it would be able to add this value to the end of the web page without needing to check through elements 50-99.



Some examples...


Code


<?php

$a = array (1, 2, 3, 17);

$i = 0;

foreach ($a as $v)

{
   echo "\$a[$i] => $v.\n<br>";
   $i++;
}

?>


Out put

$a [0] => 1.
$a [1] => 2.
$a [2] => 3.
$a [3] => 17.





Code



<? php

$a = array ("one" => 1,"two" => 2,"three" => 3,"seventeen" => 17);

foreach ($a as $k => $v)

{
   echo "\$a[$k] => $v.\n<br>";
}

?>

Out put

$a [one] => 1.
$a [two] => 2.
$a [three] => 3.
$a [seventeen] => 17.


Code


<?php

foreach (array(1, 2, 3, 4, 5) as $v)
 {
      echo “$v <br>”;
 }

?> 


Out put

1
2
3
4
5




Foreach loop is also very useful for multi dimensional array. Here is an example


Code


<?php

$a = array ();
$a [0][0] = “a”;
$a [0][1] = “b”;
$a [1][0] = “y”;
$a [1][1] = “z”;

foreach ($a as $v1)

{
   foreach ($v1 as $v2)
  
   {
       echo “$v2\n<br>”;
   }
}

?>




Output

a
b
y
z



Foreach works only on arrays, and will issue an error when we try to use it on a variable with a different data type or an uninitialized variable.

No comments:

Post a Comment