3

Why doesn't php support this syntax:

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

?

Bart Kiers
  • 166,582
  • 36
  • 299
  • 288
lost3den
  • 815
  • 1
  • 6
  • 6
  • 1
    [Array Dereferencing is in trunk now](http://schlueters.de/blog/archives/138-Features-in-PHP-trunk-Array-dereferencing.html) – Gordon Nov 09 '10 at 20:05
  • possible duplicate of [How to avoid temporary variables in PHP when using an array returned from a function](http://stackoverflow.com/questions/1769020/how-to-avoid-temporary-variables-in-php-when-using-an-array-returned-from-a-func) – Gordon Mar 05 '13 at 09:55

4 Answers4

8

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.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
5

You can write it using list:

list($first_value) = explode(‘-’,‘foo-bar’);
Ivan Nevostruev
  • 28,143
  • 8
  • 66
  • 82
0

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’);
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
0

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 !


Darkyo
  • 83
  • 8