Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning arrays in php causes syntax error

Tags:

php

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 '['
like image 705
binarypie Avatar asked Jan 23 '23 00:01

binarypie


1 Answers

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.

like image 54
John Kugelman Avatar answered Jan 31 '23 18:01

John Kugelman