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

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));

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.

Tags:

Php

Arrays