PHP Array Syntax Parse Error Left Square Bracket “

2020-01-24 16:47发布

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?

2条回答
叼着烟拽天下
2楼-- · 2020-01-24 17:23

You can't use function array dereferencing

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

until PHP 5.4.0 and above.

查看更多
混吃等死
3楼-- · 2020-01-24 17:23

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

Function array dereferencing has been added, e.g. foo()[0].

http://php.net/manual/en/migration54.new-features.php

查看更多
登录 后发表回答