foreach loop an easy way to iterate over arrays.It is used only on arrays and objects to iterate the value.
Syntax:- this syntax represent only each iteration value.
foreach (iterable_expression as $value)
statement
Example:-
Suppose, You have game_arr variable which has 4 game and now iterate the game through foreach loop.
<?php
$game_arr=array('Hockey','Cricket','Tennis','Football');
foreach($game_arr as $game_name){
echo $game_name.'<br/>';
}
?>
Hockey
Cricket
Tennis
Football
Cricket
Tennis
Football
Syntax:- this syntax represent current element’s key to the $key variable on each iteration.
foreach (iterable_expression as $key => $value)
statement
Example:-
Suppose, You have game_arr variable which has 4 game and now iterate the game through foreach loop.
<?php
$game=array('Hockey','Cricket','Tennis','Football');
foreach($game as $key => $game_name){
echo $game_name.' is on array position '.$key.'<br/>';;
}
?>
Hockey is on array position 0
Cricket is on array position 1
Tennis is on array position 2
Football is on array position 3
Cricket is on array position 1
Tennis is on array position 2
Football is on array position 3