tags:

views:

98

answers:

2
function array_test()  
{ 
    return array(0, 1, 2); 
}  

echo array_test()[0];

Can anyone explain why this code doesn't work?

+6  A: 

EDIT: apparently, array dereferencing has been added now:


Original Answers:

Because there is no array dereferencing in PHP.

Quoting myself:

This has been been asked already before. The answer is no. It is not possible.

To quote Andi Gutmans on this topic:

This is a well known feature request but won't be supported in PHP 5.0. I can't tell you if it'll ever be supported. It requires some research and a lot of thought.

You can also find this request a number of times in the PHP Bugtracker. For technical details, I suggest you check the official RFC and/or ask on PHP Internals.

Gordon
Thanks for the links! array_shift seems to be a good option to access the first element (that's what I needed.)Thanks again.
Anant
@Anant, there's also the end function that may come in handy too. I've encounter similar problem too but wanted to get a value in the middle. You can read about it at http://stackoverflow.com/questions/3099598/php-explode-and-my-trouble
Alex Polo
+1  A: 

You can't chain expressions like that in PHP, so you'll have to save the result of array_test() in a variable.

Try this:

function array_test() {
  return array(0, 1, 2);
}

$array = array_test();
echo $array[0];
ashrewdmint