|
|
Tutorials » Php »
|
Topic |
What is "foreach" statement?
|
|
Explanation |
|
For Each structure is a loop structure used for arrays
Syntax1:
foreach (array_expression as $value)
statement
Syntax2:
foreach (array_expression as $key => $value)
statement
In Syntax1 the array is given by the "array expression" and each value of the elements is assigned
to "$value". Syntax2 is also similar, but only difference is that current elements key is assigned to "$value".
Example
<?php
$arr["One"]= "1";
$arr["Two"]= "2";
$arr["Three"]= "3";
foreach ($arr as $value => $key)
{
echo "The value $value, has the key $key </br>";
}
?>
Result:
The value One, has the key 1
The value Two, has the key 2
The value Three, has the key 3
In the above example the $value is preceded by "&",it means that the array is referenced, this is to make changes
to the array elements, instead of having the copy of a array. Usually reference of a $value and the last array element
remain even after the foreach loop,so to remove that we use unset().
|
|
A Note |
Learn PHP programming language tutorial with simple and neat example. Hope you enjoy this free tutorial.
Do give us your valuable feedback and suggestions on this online tutorial. This is a Copyright Content.
|
|
|
|