How to use explode and get the first element on one line in PHP?

$beforeDot = explode(".", $string)[0]; 

This is what I am trying to do, except that it returns a syntax error. If you have a workaround for one liner, please let me know. If this is not possible, explain.

+6
source share
5 answers

function array unlocking was implemented in PHP 5.4, so if you are using an older version, you will have to do it differently.

Here is an easy way to do this:

 $beforeDot = array_shift(explode('.', $string)); 
+7
source

You can use list for this:

 list($first) = explode(".", "foo.bar"); echo $first; // foo 

This also works if you need a second (or third, etc.) element:

 list($_, $second) = explode(".", "foo.bar"); echo $second; // bar 

But it can become quite awkward.

+5
source

Use array_shift() for this:

 $beforeDot = array_shift(explode(".", $string)); 
+2
source

in php <= 5.3 you need to use

 $beforeDot = explode(".", $string); $beforeDot = $beforeDot[0]; 
+1
source

Use current () to get the first position after the explosion:

 $beforeDot = current(explode(".", $string)); 
+1
source

All Articles