Monday, February 21, 2011

Using arrays by reference in PHP

Hi,

Why is the following code "crashing" in PHP?:

$normal_array       = array();
$array_of_arrayrefs = array( &$normal_array );

end( $array_of_arrayrefs )["one"] = 1; // choking on this one

The expected result is that the final code line appends $normal_array with key "one" having value 1. In the real context of this scenario I use end() function to always append to the last array reference.

This is PHP5 by the way.


Thanks for your reply Konrad.

Then I bend the question slightly. How can I push array-references to an array and then using them from that array as references?

Regards

/R

From stackoverflow
  • This doesn't crash, it just contains a syntax error:

    end( $array_of_arrayrefs )["one"] = 1;
    

    Unfortunately, you cannot treat function return values as arrays in PHP. You have to assign the value explicitly. Unfortunately, this doesn't work here because end makes a copy of the returned value.

  • Created a new post instead:

    link text

0 comments:

Post a Comment