Share via:

PHP: Foreach

How to use the PHP Foreach loop construct to iterate over arrays.

50 views

Edited: 2019-11-03 18:31

PHP tutorial

In PHP we also have the foreach loop, which is a developer-friendly loop construct that allows to iterate over arrays and objects.

The advantage of using a foreach loop instead of a while or for, is that it is easier to use, since the array iteration happens automatically, without the need to think about counters or missing array keys.

$some_array = array('Apple', 'Banana', 'Orange', 'Carrot', 'Spinach');

foreach ($some_array as $key => $value) {
    echo PHP_EOL . $key . ':' . $value;
}

Output:

0:Apple
1:Banana
2:Orange
3:Carrot
4:Spinach

As an alternative to foreach, you could also use array_walk with an anonymous function:

array_walk($some_array, function ($value, $key) {
    echo PHP_EOL . $key . ':' . $value;
});

Comments