|
| HOW TO USE foreach LOOPS IN PHP
Foreach loops can only be used on arrays. It is used to loop through the elements of an array. This is useful as we can then perform some action with those values. It will only stop looping when it has gone through every element of that array.
There are two methods.
Method 1:
The general format is:
foreach (array_expression as $value)
{
code to execute;
}
Example:
$myArray=array('blue', 'green', 'red', 'yellow');
foreach ($myArray as $value)
{
echo "My favorite color is: ".$value."<br>";
}
This will be outputted:
My favorite color is: blue
My favorite color is: green
My favorite color is: red
My favorite color is: yellow
Method 2:
This method does the same as the first but the elements key is also assigned.
The general format is:
foreach (array_expression as $key => $value)
{
code to execute;
}
Example 1:
$myArray=array('blue', 'green', 'red', 'yellow');
Before we go any further, we need to mention that when the array was declared as above, the elements blue, green, red and yellow were each assigned a key of 0, 1, 2 and 3 respectively. (The first element is always assigned a numerical key of 0 by default).
So, the array above can also be expressed as follows:
$myArray[0] = 'blue';
$myArray[1] = 'green';
$myArray[2] = 'red';
$myArray[3] = 'yellow';
So $key comes from the indices ie. in this case, the numbers between the[ ].
foreach ($myArray as $key => $value)
{
echo $key." ".$value."<br>";
}
This will be outputted:
0 blue
1 green
2 red
3 yellow
Example 2:
Now consider this array:
$myArray=array('blue' => 'socks', 'green' => 'shirt','red' => 'tie', 'yellow' => 'hat');
The elements in the array have this pattern: $key => $value
foreach ($myArray as $key => $value)
{
echo $key." ".$value."<br>";
}
This will be outputted:
blue socks
green shirt
red tie
yellow hat
 |
|
|