Parse error on explode('-','foo-bar')[0] (for instance)

前端 未结 4 1566
暗喜
暗喜 2020-12-11 22:46

Why doesn\'t php support this syntax:

$s = explode(\'-\', \'foo-bar\')[0];

?

相关标签:
4条回答
  • 2020-12-11 23:11

    You can write it using list:

    list($first_value) = explode(‘-’,‘foo-bar’);
    
    0 讨论(0)
  • 2020-12-11 23:15

    It's a limitation in the PHP parser. There's no reason why it can't support this form of reduction, it just doesn't.

    0 讨论(0)
  • 2020-12-11 23:19

    The syntax ‘foo-bar’)[0] is wrong as far as php is concerned. I don't know which language you have seen such thing in but PHP has no implementation for such syntax. However, you can split your string like this:

    explode(‘-’, ‘foo-bar’);
    
    0 讨论(0)
  • 2020-12-11 23:23

    Instead you could use this if you'r force to use inline : substr($var,0, strrpos($var,'-')); But I prefer the list solution , it's more elegant !


    0 讨论(0)
提交回复
热议问题