Tuesday, 20 November 2018

PHP Array Syntax Parse Error Left Square Bracket "["





I have a function that returns an array. I have another function that just returns the first row, but for some reason, it makes me use an intermediate variable, i.e. this fails:



function f1(/*some args*/) {
return /*an array*/;
}
function f2(/*some args*/) {
return f1(/*some args*/)[0];
}



. . . with:




Parse error: syntax error, unexpected '[' in util.php on line 10




But, this works:



function f1(/*some args*/) {
return /*an array*/;

}
function f2(/*some args*/) {
$temp = f1(/*some args*/);
return $temp[0];
}


I wasn't able to find anything pertinent online (my searches kept getting confused by people with "?", "{", "<", etc.).



I'm self-taught in PHP - is there some reason why I can't do this directly that I've missed?



Answer



You can't use function array dereferencing



return f1(/*some args*/)[0];


until PHP 5.4.0 and above.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...