Foreach loops
The foreach loop is a 'special' type of loop for arrays (and, as of PHP5, objects). They provide an easy way to loop through all elements of an array.
Syntax
There are two syntaxes for the foreach loop, the first makes only the array values available to the loop content whilst the second makes both the array keys and values available:
<?
/* syntax 1 */
foreach($array as $value)
{
// do something
}
/* syntax 2 */
foreach($array as $key => $value)
{
// do something
}
?>
As you can see the syntax is pretty simple. Both $key and $value can be changed to any valid variable name you wish. They will be assigned the value of the key and value of the current array item as demonstrated in the below example.
Examples
The following PHP will just output the array values:
<?
$array = array(1, 2, 3, 4, 5);
foreach($array as $value)
{
echo $value;
}
?>
This will output:
12345
In this second example the array keys and values are outputted:
<?
$my_array = array('a' => 1, 'b' => 2, 'c' => 3);
foreach($my_array as $letter => $number)
{
echo $letter . ':' . $number . '<br />';
}
?>
This PHP will output the following:
a:1
b:2
c:3
Foreach with objects
As of PHP5 foreach also works with objects and will iterate through all visible variables that can be accessed:
<?
class example
{
public $variable = 0;
public $another = 'hello';
public $athird = 'world';
public $last = 3.14159;
function example_method()
{
echo 'Hello world!';
}
}
$object = new example();
foreach($object as $key => $value) {
echo $key . ':' . $value . '<br />';
}
?>
This would output:
variable:0
another:hello
athird:world
last:3.14159
And that is the foreach loop!
