4
function get_arr() {
    return array("one","two","three");
}

echo get_arr()[0];

Why does the above code throw the following error?

parse error: syntax error, unexpected '['
Ates Goral
  • 137,716
  • 26
  • 137
  • 190
binarypie
  • 43
  • 4
  • possible duplicate of [PHP Array Syntax Parse Error Left Square Bracket "\["](http://stackoverflow.com/questions/11912233/php-array-syntax-parse-error-left-square-bracket) – Ja͢ck Mar 11 '14 at 04:49

6 Answers6

7

This is simply a limitation of PHP's syntax. You cannot index a function's return value if the function returns an array. There's nothing wrong with your function; rather this shows the homebrewed nature of PHP. Like a katamari ball it has grown features and syntax over time in a rather haphazard fashion. It was not thought out from the beginning and this syntactical limitation is evidence of that.

Similarly, even this simpler construct does not work:

// Syntax error
echo array("one", "two", "three")[0];

To workaround it you must assign the result to a variable and then index the variable:

$array = get_arr();
echo $array[0];

Oddly enough they got it right with objects. get_obj()->prop is syntactically valid and works as expected. Go figure.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • Thank you for taking the time to actually confirm my suspicion. – binarypie Nov 10 '09 at 19:40
  • +1 for Katamari reference <3, Also you can cast your array to an object `return (object) $result` PHP documentation: "Arrays convert to an object with properties named by keys, and corresponding values." http://php.net/manual/en/language.types.object.php – nuala Apr 08 '13 at 09:31
2

You can't directly reference returned arrays like that. You have to assign it to a temporary variable.

$temp = get_arr();
echo $temp[0];
davethegr8
  • 11,323
  • 5
  • 36
  • 61
0

"because you can't do" that isn't a very satifying answer. But that's the case. You can't do function_which_returns_array()[$offset]; You have to store the return value in a $var and then access it.

dnagirl
  • 20,196
  • 13
  • 80
  • 123
0

I am pretty sure if you do :

$myArray = get_arr();
echo $myArray[0];

That it will works. You cannot use braket directly.

Patrick Desjardins
  • 136,852
  • 88
  • 292
  • 341
0

Indeed, you are not the only one to want such a feature enhancement: PHP Bug report #45906

dustmachine
  • 10,622
  • 5
  • 26
  • 28
0

you can also do

 list($firstElement) = get_arr();
user187291
  • 53,363
  • 19
  • 95
  • 127