Home >>PHP Tutorial >PHP Foreach Loop

PHP Foreach Loop

Foreach Loop in PHP

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).

Syntax
	foreach ($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/>";
  	
} 
 
?>
Output
alex
simon
ravi
In the above example,
declare an array variable($person) hold the elements of array. Here we want to print all element of an array without passing index value.
We used foreach( ) loop. Passing Variable name ($person as $val).
it means $val collect all elements of an array. Pass $val with echo statement it show all element as output.

Define colors name and their index

<?php
	
$color=array("r"=>"red", "g"=>"green","b"=>"black","w"=>"white");
	
foreach ($color as $key=>$val)
  	
{
	 
echo $key."--".$val."<br/>";
  	
} 

?>
Output
r--red
g--green
b--black
w--white
In the above example,
$color variable hold the values ("red","green","black","white") on index("r", "g", "b", "w" ).
if we want do display all values with their index then used foreach( ) loop.
Inside foreach( ) we have passed three arguments array name, index($key) and value($val) separated by "as".
Now call the variable $val to display array values and $key for index.

Find the Sum of given array

 <?php
	
$array=array(10,11,12,13,14,15);
	
$sum=0;
      
 foreach ($array as $x)
  	
{
       
 $sum=$sum+$x;
  	
} 
      
 echo "Sum of given array = ".$sum;

?>
Output
Sum of given array = 75
In the above example,
Declare variable $array hold the elements of an array, variable $sum hold value=0,
pass( $array as $x) inside foreach( ) loop.
It call the values of array one by one and make sum ($sum=$sum+$x) till ends of array.
at last pass $sum with echo statement to display the sum of given array, output will become.

No Sidebar ads