What potential pitfalls should be avoided when manipulating arrays in PHP?

When manipulating arrays in PHP, it is important to avoid directly modifying the array while iterating over it, as this can lead to unexpected results or errors. Instead, it is recommended to create a copy of the array before modifying it to prevent any unintended consequences. Additionally, be cautious when using functions that alter the internal pointer of the array, as this can affect the iteration process.

// Avoid directly modifying an array while iterating over it
$array = [1, 2, 3, 4, 5];
foreach ($array as $key => $value) {
    unset($array[$key]); // This can lead to unexpected results
}

// Instead, create a copy of the array before modifying it
$array = [1, 2, 3, 4, 5];
$copy = $array;
foreach ($copy as $key => $value) {
    unset($array[$key]); // Safe to modify $array
}

// Be cautious when using functions that alter the internal pointer of the array
$array = [1, 2, 3, 4, 5];
reset($array); // Reset internal pointer
foreach ($array as $value) {
    // Code here
}