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 '['
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 '['
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.
You can't directly reference returned arrays like that. You have to assign it to a temporary variable.
$temp = get_arr();
echo $temp[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.
I am pretty sure if you do :
$myArray = get_arr();
echo $myArray[0];
That it will works. You cannot use braket directly.
Indeed, you are not the only one to want such a feature enhancement: PHP Bug report #45906