Emanuil Rusev
Emanuil Rusev

Reputation: 35265

Explode and get a value in one line of code

Can you write the following in one line of code?

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

Upvotes: 19

Views: 10677

Answers (4)

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;

Upvotes: 0

qualbeen
qualbeen

Reputation: 1582

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

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

Upvotes: 7

GSto
GSto

Reputation: 42370

you could use stristr for this:

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

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

Upvotes: 21

Ivan Nevostruev
Ivan Nevostruev

Reputation: 28733

Yes, it's posible to do using list:

list($foo) = explode(":", $foo);

Upvotes: 5

Related Questions