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?
You can't use function array dereferencing
until PHP 5.4.0 and above.
The reason for this behavior is that PHP functions can't be chained like JavaScript functions can be. Just like
document.getElementsByTagNames('a')[0]
is possible.You have to stick to the second approach for PHP version < 5.4
http://php.net/manual/en/migration54.new-features.php