Foreach Loop 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
The following example demonstrates a loop that will print the values of the given array.
Output
alex
simon
ravi
In the above examplealex
simon
ravi
declare an array variable($person) hold the elements of array. Here we want to print all element of an array without passing index value.
We used foreach( ) loop. Passing Variable name ($person as $val).
it means $val collect all elements of an array. Pass $val with echo statement it show all element as output.
Define colors name and their index
Output
r–red
g–green
b–black
w–white
In the above exampler–red
g–green
b–black
w–white
$color variable hold the values (“red”,”green”,”black”,”white”) on index(“r”, “g”, “b”, “w” ).
if we want do display all values with their index then used foreach( ) loop.
Inside foreach( ) we have passed three arguments array name, index($key) and value($val) separated by “as”.
Now call the variable $val to display array values and $key for index.
Find the Sum of given array
Output
Sum of given array = 75
In the above exampleSum of given array = 75
Declare variable $array hold the elements of an array, variable $sum hold value=0,
pass( $array as $x) inside foreach( ) loop.
It call the values of array one by one and make sum ($sum=$sum+$x) till ends of array.
at last pass $sum with echo statement to display the sum of given array, output will become.
No comments:
Post a Comment