dsq1982 2014-02-05 13: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 13: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

    $exploded = explode('-', $str);
    $first = $exploded[0];
    // or
    list($first,) = explode('-', $str);
    

    In PHP 5.4 and later you can use

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

报告相同问题?

悬赏问题

  • ¥15 蓝桥oj3931,请问我错在哪里
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染