PHP foreach loop



PHP foreach loop

In foreach loop used in on array.
In foreach loop each element of array is assigned to $value and we can use $value in program then assigned each element one by one to $value from an array.

PHP foreach loop syntax:

foreach (array as value)
{
//bock of code to be executed
}

Exmaple of foreach loop

<?php

$arr = array(1,2,3,4,5);
foreach($arr as $value)
{
echo $value;
}

?>

The output is: 12345

In above example first we declare array with five elements, foreach loop assigned all element of array one by one to $value and echo statement print $value, so the foreach loop repeat five times and we get result : 12345

Example of foreach loop

<?php

$arr = array(1,2,3,4,5);
foreach($arr as $value)
{
echo $value * 3;
}
?>

The output is : 3 6 9 12 15

PHP foreach example

<?php

$sum=0;
$arr = array(1,2,3,4,5);
foreach($arr as $value)
{
$sum =$sum +$value;
}
echo “The sum of array element is = ” .$sum;
?>

The output is :
The sum of array element is = 15

PHP foreach loop example for find out odd and even elements from an array.

<?php

$even=””;
$odd=””;
$arr = array(1,2,3,4,5);
foreach($arr as $value)
{

if($value%2==0)
{
$even=$even .” ” . $value;
}
else
{
$odd=$odd . ” “.$value;
}

}
echo “The even elements are = ” .$even . “<br/>”;
echo “The odd elements are = ” .$odd ;
?>

The even elements are = 2 4
The odd elements are = 1 3 5

Leave a Reply

Your email address will not be published. Required fields are marked *