Logo


PHP Loop Foreach



PHP Foreach Loop

1.The foreach loop is used to loop through arrays.

2.In the enhanced for loop, the array index is not necessary for the retrieval of an array element.


Syntax:
foreach ($array_variable as $value)
{
  [code to execute]
}

or
foreach ($array_variable as $key => $value)
{
  [code to execute]
}

Example: 1
<?php
$x
=array(1,2,3,4,5);

foreach (
$x as $key=>$value)
{
echo 
$key " = ".$value "<br />";
}
?>
Output
0 = 1
1 = 2
2 = 3
3 = 4
4 = 5    


Example: 2
<?php
$required_fields 
= array(
"Oliva" => "School",
"Nicole" => "College",
"Natasha" => "University"
);

foreach (
$required_fields as $key=>$value) {
print(
$key": study in " $value "<br/>");
}
?>
Output
Oliva: study in School
Nicole: study in College
Natasha: study in University


Example: 3
<?php
$required_fields 
= array("name" => "Paul""age" => 23);

foreach (
$required_fields as $key=>$value) {
    print 
"$key = $value<br/>";
}
?>
Output
name = Paul
age = 23


Example: 4
<?php
$required_fields
["Oliva"] = "School";
$required_fields["Nicole"] = "College";
$required_fields["Natasha"] = "University";

foreach( 
$required_fields as $key => $value){
    echo 
"Key: $key, Value: $value <br />";
}
?>
Output
Key: Oliva, Value: School 
Key: Nicole, Value: College 
Key: Natasha, Value: University 


Example: 5
<?php
$array 
= array("1st" => "My House""2nd" => "My Car""3rd" => "My Lab");
foreach (
$array as $key => $value) {
  echo 
$key ": " $value "<br />\n";
}
?>
Output
1st: My House
2nd: My Car
3rd: My Lab



If you like this Article, Share and Enjoy



See Also
For Loop
While Loop
Do While Loop