views:

137

answers:

3

Can you write the following in one line of code?

$foo = explode(":", $foo);
$foo = $foo[0];
+3  A: 

Yes, it's posible to do using list:

list($foo) = explode(":", $foo);
Ivan Nevostruev
Thanks, that's a nice approach. However, I'd love to see an approach that doesn't require additional methods. Something like explode(":", $foo)[0];
Emanuil
PHP doesn't support that syntax. You're forced to do what you want to do in 2 lines.
Nick Presta
I think PHP doesn't allow `...[0]` code unlike Python or Perl. And that's why `list` was added into language.
Ivan Nevostruev
+4  A: 

you could use stristr for this:

$foo = stristr($foo,":",true);

where true sets it to give you everything before the first instance of ":"

GSto
Thank you, that's beautiful.
Emanuil
Just be aware this will only work in PHP 5.3.0 and higher.
pw
+1  A: 

As an alternative to list(), you may use array_shift()

$foo = array_shift(explode(':', $foo));
qualbeen