The foreach statement is used to loop through arrays. For each pass, the value of the current array element is assigned to $value and the array pointer is moved by one and in the next pass next element will be processed.
foreach (array as value) {
code to be executed;
}
foreach Loop Explanation
<?php
$days= array("Sunday", "Monday", "Tuesday");
// Loop through colors array
foreach($days as $value){
echo $value . "<br>";
}
?>
Output :
Sunday
Monday
Tuesday
<?php
$Mydata= array(
"name" => "Admin",
"email" => "admin@esaytolearning.com",
"age" => 22
);
// Loop through Mydata array
foreach($Mydataas $key => $value){
echo $key . " : " . $value . "<br>";
}
?>
Output :
name : Admin
email : admin@easytolearning.com
age : 22
We can use for loop inside for loop in PHP, it is known as nested for loop.
Nested for loop is executed fully for one outer for loop. If outer for loop is to be executed 3 times and inner for loop for 3 times, inner for loop will be executed 9 times (3 times for 1st outer loop, 3 times for 2nd outer loop and 3 times for 3rd outer loop).
<?php
for($i=1;$i<=3;$i++){
for($j=1;$j<=3;$j++){
echo "$i $j<br/>";
}
}
?>
Output :
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
PHP foreach Loop,foreach loop statement,PHP nested for loop
© 2024 Easy To Learning. All Rights Reserved | Design by Easy To Learning