tags:

views:

63

answers:

4

Why doesn't php support this syntax:

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

?

+4  A: 

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
A: 

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
`$ python -c "print 'foo-bar'.split('-')[0]"``foo`
Ignacio Vazquez-Abrams
@Ignacio Vazquez-Abrams : thanks for sharing that :)
Sarfraz
pretty much every other c-alike language supports that.
stereofrog
That works in C language
lost3den
+5  A: 

You can write it using list:

list($first_value) = explode(‘-’,‘foo-bar’);
Ivan Nevostruev
Yes, of course, but I was just wondering why it doesn't work in the case of php
lost3den
A: 

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