PHP foreach


Example

foreach is a construct, which enables you to iterate over arrays and objects easily.

$array = [1, 2, 3];
foreach ($array as $value) {
    echo $value;
}

Outputs: 123.

To use foreach loop with an object, it has to implement Iterator interface.

When you iterate over associative arrays:

$array = ['color'=>'red']; 

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

Outputs: color: red

For detailed information, see the Loops topic.