Home >>PHP Tutorial >PHP Foreach Loop
The foreach Loop is used to display the value of array.
You can define two parameter inside foreach separated through "as" keyword. First parameter must be existing array name which elements or key you want to display.
At the Position of 2nd parameter, could define two variable: One for key(index) and another for value.
if you define only one variable at the position of 2nd parameter it contain arrays value (By default display array value).
Syntaxforeach ($array as $value) { code to be executed; }
For every loop iteration, the value of the current array element is assigned to $value (and the array pointer is moved by one) - so on the next loop iteration, you'll be looking at the next array value.
The following example demonstrates a loop that will print the values of the given array.<?php $person=array("alex", "simon","ravi"); foreach ($person as $val) { echo $val."<br/>"; } ?>
<?php $color=array("r"=>"red", "g"=>"green","b"=>"black","w"=>"white"); foreach ($color as $key=>$val) { echo $key."--".$val."<br/>"; } ?>
<?php $array=array(10,11,12,13,14,15); $sum=0; foreach ($array as $x) { $sum=$sum+$x; } echo "Sum of given array = ".$sum; ?>