我有时会从这样的数组中获取值:$var = array ('key1' => 'value1')['key1'];
,所以$var
应该等于value1
我在具有PHP v5.4.16的服务器中运行这样的代码,例如explode ('-', $str)[0];
,并且运行良好。
现在,如果我将此代码传输到另一个使用PHP v5.3.10的服务器,则会收到错误(syntax error): syntax error, unexpected '[' ...
是因为版本吗? (我不这么认为,因为版本之间的差异非常小..),还是服务器中的某些设置?
谁能启发我?
最佳答案
是的,这取决于您正在运行的PHP版本。作为PHP docs mentions
As of PHP 5.4 it is possible to array dereference the result of a function or method call directly. Before it was only possible using a temporary variable.
As of PHP 5.5 it is possible to array dereference an array literal.
在PHP 5.3中,您必须使用
$exploded = explode('-', $str);
$first = $exploded[0];
// or
list($first,) = explode('-', $str);
在PHP 5.4和更高版本中,您可以使用$first = explode('-', $str)[0];
关于php - 不同版本的PHP语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21578437/