Explode and get a value in one line of code
Asked Answered
C

4

19

Can you write the following in one line of code?

$foo = explode(":", $foo);
$foo = $foo[0];
Cantoris answered 16/11, 2009 at 21:25 Comment(2)
See: #13609Turkoman
In PHP 5.4 you can!Halvorson
F
21

you could use stristr for this:

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

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

Fibster answered 16/11, 2009 at 21:34 Comment(1)
how can i get 2nd element using this ? it throws first element only.Helle
A
7

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

$foo = array_shift(explode(':', $foo));
Apartment answered 16/11, 2009 at 23:37 Comment(0)
B
5

Yes, it's posible to do using list:

list($foo) = explode(":", $foo);
Beatty answered 16/11, 2009 at 21:27 Comment(3)
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];Cantoris
PHP doesn't support that syntax. You're forced to do what you want to do in 2 lines.Turkoman
I think PHP doesn't allow ...[0] code unlike Python or Perl. And that's why list was added into language.Beatty
R
0

Just completing @GSto answer, in case it helps:
I often have to deal with strings that can have 0 or more separators (colon in this example).

Here is a one-liner to handle such strings:

$first = stristr($foo,":") ? stristr($foo,":",true) : $foo;
Richma answered 12/4, 2020 at 19:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.