PHP: undefined offset in explode()

Karem picture Karem · Jul 14, 2011 · Viewed 13.2k times · Source

I have this:

list($firstname, $lastname) = explode(' ', $queryString);

Sometiems $lastname does not gets defined, and it's there i am getting undefined offset error.

Because it can not find anything to put in $lastname, i guess.

After the explode() i have:

if(!$lastname) { $lastname = $firstname; }

So my question is how can i define it as the $firstname if $lastname is not defined (if you wrote only 'Adam' and not 'Adam Thompson', the lastname should be defined so it is 'Adam Adam')

It does this for me now, but I am receiving the offset error

Answer

KingCrunch picture KingCrunch · Jul 14, 2011
list($firstname, $lastname) = array_pad(explode(' ', $queryString, 2), 2, null);

The 2 in explode() ensures, that there are at most 2 values and array_pad() ensures, that there are at least 2 values. If there is no space character , $lastname is null. This you can use to decide what comes next

$lastname = is_null($lastname) ? $firstname : $lastname;

Little update: For this specific case you can use a little trick

list($firstname, $lastname) = array_pad(explode(' ', $queryString, 2), 2, $queryString);

This will do all that in one step. It should work, because

  • There is always at least one value (for $firstname)
  • If there is one value, then $queryString == $firstname. Thats now the value that is used to fill the array up to 2 values (which is exactly one, because one value we already have)
  • If there are two values, then the array is not filled with $queryString, because we already have 2 values

At least for readability I would prefer the first more obvious solution.