Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php fault? Are php reference so strange to manage?

Tags:

php

I found a snippet of code in php documentation that I don't understand. I really don't understand if it is a php failure or a shortcoming of mine.

Here the code:

$arr = array('a'=>'first', 'b'=>'second', 'c'=>'third');
foreach ($arr as &$a); // do nothing. maybe?
foreach ($arr as $a);  // do nothing. maybe?
print_r($arr);
?>

Output:

Array
(
    [a] => first
    [b] => second
    [c] => second
)

Add 'unset($a)' between the foreachs to obtain the 'correct' output:

Array
(
    [a] => first
    [b] => second
    [c] => third
)

link: http://php.net/manual/en/language.references.php

Why this behavior? Thanks in advance

like image 399
vitosdc Avatar asked Feb 12 '23 04:02

vitosdc


1 Answers

foreach ($arr as &$a); // do nothing. maybe?
                 ^---

Once you create a variable as a reference, it STAYS a reference. So in your next foreach, $a will be pointing at the last element of $arr, as it was when the first foreach finished.

Doing unset() in between removes the reference.

like image 180
Marc B Avatar answered Feb 13 '23 22:02

Marc B