The Foreach loop is a variation of the For loop and allows you to iterate over elements in an array. There are two different versions of the Foreach loop.
The Foreach loop syntax's are as follows:
PHP executes the body of the loop once for each element of $email in turn, with $value set to the current element. Elements are processed by their internal order. Looping continues until the Foreach loop reaches the last element or upper bound of the given array.
An alternative form of Foreach loop gives you access to the current key:
<?php
The Foreach loop syntax's are as follows:
foreach (array as value)
{
code to be
executed;
}
foreach (array as key => value)
{
code to be
executed;
}
The example below demonstrates the Foreach loop that will print the values of the given array:
<?php
$email = array('xxxxxxx @example.com',
'yyyyyyyy@example.com');
foreach ($email as $value) {
echo "Processing
".$value."<br />";
}
?>
PHP executes the body of the loop once for each element of $email in turn, with $value set to the current element. Elements are processed by their internal order. Looping continues until the Foreach loop reaches the last element or upper bound of the given array.
An alternative form of Foreach loop gives you access to the current key:
<?php
$person = array('name' => 'xxxxxx',
'age' => 22, 'address' => '75, yyyyyy z.');
foreach ($person as $key =>
$value) {
echo $key." is
".$value."<br />";
}
?>
In this case, the key for each element is placed in $key and the corresponding value is placed in $value.
The Foreach construct does not operate on the array itself, but rather on a copy of it. During each loop, the value of the variable $value can be manipulated but the original value of the array remains the same.
Comments
Post a Comment