PHP foreach


Example

The foreach statement is used to loop through arrays.

For each iteration the value of the current array element is assigned to $value variable and the array pointer is moved by one and in the next iteration next element will be processed.

The following example displays the items in the array assigned.

$list = ['apple', 'banana', 'cherry'];

foreach ($list as $value) {
    echo "I love to eat {$value}. ";
}

The expected output is:

I love to eat apple. I love to eat banana. I love to eat cherry. 

You can also access the key / index of a value using foreach:

foreach ($list as $key => $value) {
    echo $key . ":" . $value . " ";
}

//Outputs - 0:apple 1:banana 2:cherry

By default $value is a copy of the value in $list, so changes made inside the loop will not be reflected in $list afterwards.

foreach ($list as $value) {
    $value = $value . " pie";
}
echo $list[0]; // Outputs "apple"

To modify the array within the foreach loop, use the & operator to assign $value by reference. It's important to unset the variable afterwards so that reusing $value elsewhere doesn't overwrite the array.

foreach ($list as &$value) { // Or foreach ($list as $key => &$value) {
    $value = $value . " pie";
}
unset($value);
echo $list[0]; // Outputs "apple pie"

You can also modify the array items within the foreach loop by referencing the array key of the current item.

foreach ($list as $key => $value) {
    $list[$key] = $value . " pie";
}
echo $list[0]; // Outputs "apple pie"