27 Nov

PHP Gotcha – foreach with pass by reference

We can pass by reference the values in an array to modify the array. But in the following code snippet, the output will be somewhat erratic.  

$someArray = array(1,2,3);
foreach($someArray as &$value) {
   $value++;
}

$value++;
print_r($value);

The output is

array(2,3,5)

As you noticed the last value is incremented twice, because the reference is not lost after the loop ends. The increment $value++ outside the loop will update the last reference viz the last element. To avoid this one must unset your last used reference

$someArray = array(1,2,3);
foreach($someArray as &$value) {
   $value++;
}

unset($value);
$value++;
print_r($value);

Now the output will be

array(2,3,4)