References in Foreach in PHP
When working with the foreach
loop,
changing the variable for elements
does not lead to changes in the array itself:
<?php
$arr = [1, 2, 3, 4, 5];
foreach ($arr as $elem) {
$elem++;
}
var_dump($arr); // will not change
?>
However, the desired effect can be achieved if you declare the variable for elements as a reference. In this case, changes to this variable will lead to changes in the array:
<?php
$arr = [1, 2, 3, 4, 5];
foreach ($arr as &$elem) {
$elem++;
}
var_dump($arr); // will change
?>
Fix the following code so that it works as intended:
<?php
$arr = [1, 2, 3, 4, 5];
foreach ($arr as &$elem) {
$elem = sqrt($elem);
}
var_dump($arr);
?>
Fix the following code so that it works as intended:
<?php
$arr = [1, 2, 3, 4, 5];
foreach ($arr as &$elem) {
$elem ** 2;
}
var_dump($arr);
?>