Returned arrays in php result in syntax error

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 '['
+4
source share
6 answers

This is just a limitation of PHP syntax. You cannot index the return value of a function if the function returns an array. There is nothing wrong with your function; rather, it indicates the homegrown nature of PHP. Like the catamari step, over time it became more functional and syntactic. This was not thought out from the very beginning, and this syntactic restriction is proof of this.

Similarly, even this simpler construction does not work:

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

To get around this, you must assign the result to a variable and then index the variable:

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

Oddly enough, they correctly understood the objects. get_obj()->prop is syntactically valid and works as expected. Hover over your mouse.

+7
source

You cannot directly refer to returned arrays. You must assign it to a temporary variable.

 $temp = get_arr(); echo $temp[0]; 
+2
source

"because you cannot do it," is not a very rich answer. But this is the case. You cannot execute function_which_returns_array()[$offset]; You need to store the return value in $ var, and then get it.

0
source

I am sure if:

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

This will work. You cannot use the form directly.

0
source

In fact, you are not the only one who wants such a feature enhancement: PHP error report # 45906

0
source

you can also do

  list($firstElement) = get_arr(); 
0
source

All Articles