Logo


PHP Loop Foreach



Loop Foreach

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 $value)
{
echo 
"New value is ".$value*10 "<br />";
}
?>
Output
New value is 10
New value is 20
New value is 30
New value is 40
New value is 50


Example: 2
<?php
$x
=array(1,2,3,4,5);
foreach (
$x as $key=>$value)
{
echo 
"New value is[".$key"] = ".$value*10 "<br />";
}
?>
Output
New value is[0] = 10
New value is[1] = 20
New value is[2] = 30
New value is[3] = 40
New value is[4] = 50


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



If you like this Article, Share and Enjoy



See Also
For Loop
While Loop
Do While Loop