What are some best practices for manipulating arrays in PHP within a foreach loop?
When manipulating arrays within a foreach loop in PHP, it's important to avoid directly modifying the array being iterated over as it can lead to unexpected results. Instead, create a new array to store the modified values. This ensures that the original array remains intact and the loop operates as expected.
$originalArray = [1, 2, 3, 4, 5];
$newArray = [];
foreach ($originalArray as $value) {
// Manipulate the value
$newValue = $value * 2;
// Store the modified value in a new array
$newArray[] = $newValue;
}
// $originalArray remains unchanged
print_r($originalArray);
// $newArray contains the modified values
print_r($newArray);