Tuesday 15 March 2011

php - Alternative to foreach pass by reference -



php - Alternative to foreach pass by reference -

i've come case values in foreach passed reference in order modify element, @ later stage in code, same array looped 1 time again calculation time elements passed value. issue php retains reference lastly element in array in first foreach, overwrites element when next foreach starts if local variable has same name.

example code:

<?php $a = array("a" => "foo"); $b = array("b" => "bar"); $x = array($a, $b); foreach ($x &$y) {} print_r($x); foreach ($x $y) {} print_r($x); ?>

this yield

array ( [0] => array ( [a] => foo ) [1] => array ( [b] => bar ) ) array ( [0] => array ( [a] => foo ) [1] => array ( [a] => foo ) )

this absurdity stated in php manual

warning reference of $value , lastly array element remain after foreach loop. recommended destroy unset().

and indeed, using unset($y) resolve issue. fragile , cannot rely on coder remembering unset variable scope isn't obvious. question is: there alternatives foreach-pass-by-reference eliminates need unset variable afterwards?

you can utilize array_walk():

array_walk($x, function(&$y) { /* ... */ });

this makes reference $y local scope of callback function unsetting handled automatically.

php foreach pass-by-reference

No comments:

Post a Comment