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
Php foreach loop – Interview Questions
Q 1: What is foreach loop?
Ans: Used to iterate over arrays.
Q 2: Syntax of foreach?
Ans: foreach ($arr as $value) { }
Q 3: Can foreach access keys?
Ans: Yes.
Q 4: Is foreach faster than for loop?
Ans: Yes, for arrays.
Q 5: Can foreach modify array values?
Ans: Yes, using references.
C# Dictionary – Objective Questions (MCQs)
Q1. foreach is used to iterate over ______.
Q2. foreach($arr as $value) loops through ______.
Q3. To get both key and value, syntax is ______.
Q4. Can foreach modify the original array values?
Q5. foreach automatically stops when ______.