Skip to content
PHP Logo

What are potential pitfalls when using foreach loops in PHP?

One potential pitfall when using foreach loops in PHP is modifying the array being iterated over within the loop. This can lead to unexpected behavior or even an infinite loop. To avoid this issue, it's recommended to create a copy of the array before iterating over it.

php
// Create a copy of the array before iterating over it
$array = [1, 2, 3, 4, 5];
$arrayCopy = $array;

foreach ($arrayCopy as $value) {
    // Modify $arrayCopy instead of $array
    echo $value * 2 . PHP_EOL;
}