In a PHP foreach loop, how can specific values in an array be replaced with new values?
To replace specific values in an array during a foreach loop in PHP, you can use a reference to the array element within the loop and update its value directly. By checking for specific conditions within the loop, you can determine which values need to be replaced and assign the new values accordingly.
<?php
$array = [1, 2, 3, 4, 5];
foreach ($array as &$value) {
if ($value % 2 == 0) {
$value = $value * 2; // Replace even numbers with their double
}
}
unset($value); // Unset the reference to avoid potential side effects
print_r($array);
?>