dsq1982 2014-02-05 05:17
浏览 18
已采纳

不同版本的PHP语法错误

I sometimes get values from an array like this: $var = array ('key1' => 'value1')['key1']; , so $var should be equal to value1

I run code like this in a server having PHP v5.4.16 , for example, explode ('-', $str)[0]; and it works fine. Now if I transfer this code to another server which uses PHP v5.3.10 I get an error (syntax error): syntax error, unexpected '[' ...

Is this because of the version? (I don't think so because the difference between versions is so small..), or some setting in the server? Can anyone enlighten me?

  • 写回答

1条回答 默认 最新

  • douji9518 2014-02-05 05:21
    关注

    Yes, it depends on the version of PHP you are running. As 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.

    In PHP 5.3 you would have to use

    1. $exploded = explode('-', $str);
    2. $first = $exploded[0];
    3. // or
    4. list($first,) = explode('-', $str);

    In PHP 5.4 and later you can use

    $first = explode('-', $str)[0];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部