user3388884
user3388884

Reputation: 5088

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

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

This is what I'm attempting to do, except that it returns syntax error. If there is a workaround for a one liner, please let me know. If this is not possible, please explain.

Upvotes: 16

Views: 27436

Answers (7)

MarcoZen
MarcoZen

Reputation: 1683

Pairing 'explode' with 'implode' to populate a variable.

explode -> break the string into an array at the separator
implode -> get a string from that first array element into a variable

$str = "ABC.66778899";
$first = implode(explode('.', $str, -1));

Will give you 'ABC' as a string. Adjust the limit argument in explode as per your string characteristics.

Upvotes: 0

You can use the limit parameter in the explode function

explode($separator, $str, $limit)

$txt = 'the quick brown fox';
$explode = explode(' ', $txt, -substr_count($txt, ' '));

This will return an array with only one index that has the first word which is "the"

PHP Explode docs

Explanation:

If the limit parameter is negative, all components except the last -limit are returned.

So to get only the first element despite the number of occurences of the substr you use -substr_count

Upvotes: 0

lsouza
lsouza

Reputation: 2488

The function array dereferencing was implemented in PHP 5.4, so if you are using an older version you'll have to do it another way.

Here's a simple way to do it:

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

Upvotes: 17

abfurlan
abfurlan

Reputation: 415

Use current(), to get first position after explode:

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

Upvotes: 12

alexn
alexn

Reputation: 59002

You can use list for this:

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

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

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

But that can get pretty clumsy.

Upvotes: 12

potashin
potashin

Reputation: 44601

Use array_shift() for this purpose :

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

Upvotes: 2

Thiago França
Thiago França

Reputation: 1847

in php <= 5.3 you need to use

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

Upvotes: 1

Related Questions