PHP: strange reference variable -
as understand, when pass variable function, , if don't use reference sign (&) , means changes inside function not affect variable outside function. in other words, means compiler make copy of outside variable use inside function, doesn't it?
but when run these testing code, not happen that. can explain me miss here? thank you
my test code: expected result should 3, becomes 1?
function test($arr2) { foreach($arr2 &$item) { $item = 1; } } $arr = array(2); foreach($arr &$item2) { $item2 = 3; } test($arr); print_r($arr);
this issue has been solved few times before you've asked (#1). issue due fact that:
reference of $value , last array element remain after foreach loop. recommended destroy unset().
reference: php foreach()
you need unset last $item2
after foreach:
foreach ($arr &$item2) { $item2 = 3; } unset($item2);
Comments
Post a Comment