sharkin
sharkin

Reputation: 12498

Using arrays by reference

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 but there is no output what so ever, not even prints preceeding this code. In the real context of this scenario I use end() function to always append to the last array reference.

Upvotes: 0

Views: 690

Answers (1)

Konrad Rudolph
Konrad Rudolph

Reputation: 545518

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.

Upvotes: 3

Related Questions