Imagine a foreach with a pointer, then a foreach reusing that same variable name:
foreach($array as $k => &$v) { $v = ucfirst($v); }
foreach($array as $k => $v) {}
The first foreach
causes a pointer on $v. As soon as the second foreach
is entered, the last value of the array becomes the same as the second to last value. This is caused by the way PHP turns $v
to be pass by reference (whereas the default is pass by value), which means the second foreach will continuously update the array.
This is very easy to avoid by either not using the pointer and just doing $array[$k] = ucfirst($v);
instead of $v = ucfirst($v);
, or using a disposable variable in the first foreach that is easy to avoid. However, there are cases where using a pointer is valid, and it raises the following question;
Is it possible to unset a reference in PHP without destroying the value?
The PHP docs on Passing by Reference and Unsetting References do show what references are in PHP, but don't really explain a way to return them to normal variables. I have searched outside of the PHP docs, but I cannot find any solid answers on this. It seems impossible, but it almost can't be, as it's such a core language feature (especially through the global
keyword).