19

Can you write the following in one line of code?

$foo = explode(":", $foo);
$foo = $foo[0];
Emanuil Rusev
  • 34,563
  • 55
  • 137
  • 201

4 Answers4

21

you could use stristr for this:

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

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

GSto
  • 41,512
  • 37
  • 133
  • 184
  • how can i get 2nd element using this ? it throws first element only. –  Jul 29 '14 at 05:33
7

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

$foo = array_shift(explode(':', $foo));
qualbeen
  • 1,534
  • 4
  • 16
  • 27
5

Yes, it's posible to do using list:

list($foo) = explode(":", $foo);
Ivan Nevostruev
  • 28,143
  • 8
  • 66
  • 82
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;
Cédric Françoys
  • 870
  • 1
  • 11
  • 22