What are some common pitfalls when using foreach loops in PHP?

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

// 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 . "\n";
}