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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With