Home Blog foreach Loop Statement in PhP

foreach Loop Statement in PhP

0
foreach Loop Statement in PhP

The foreach Loop is used to display the value of array. You can define two parameter inside foreach separated through “as” keyword. First parameter must be existing array name which elements or key you want to display. At the Position of 2nd parameter, could define two variable: One for key(index) and another for value.

if you define only one variable at the position of 2nd parameter it contain arrays value (By default display array value).

Syntax

foreach ($array as $value) {
   code to be executed;
}

In the following example to list out the values of an array

<?php
 $array = array( 1, 2, 3, 4, 5);
   
 foreach( $array as $value ) {
 echo "Value is $value <br />";
 }
 ?>

Output
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5

The following example demonstrates a loop that will output the values of the given array ($colors)

<?php
$colors = array("red", "green", "blue", "yellow");

foreach ($colors as $value) {
    echo "$value <br>";
}
?>

Output

red
green
blue
yellow

Example to find the Sum of given array

<?php
$array=array(10,11,12,13,14,15);
$sum=0;
 foreach ($array as $x)
{
 $sum=$sum+$x;
} 
 echo "Sum of given array = ".$sum;
?>

Output: Sum of given array = 75

LEAVE A REPLY

Please enter your comment!
Please enter your name here