What are the 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 and errors. To avoid this issue, it's recommended to create a copy of the array before iterating over it. Another common pitfall is not resetting the internal array pointer after the loop, which can cause issues if the array is used again later in the code.

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

foreach ($copy as $value) {
    // Loop through the copied array
    echo $value . "\n";
}