PHP: undefined offset in explode() PHP: undefined offset in explode() php php

PHP: undefined offset in explode()


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.


Try appending a space:

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

shouldn't have to change a thing after that.


You're not getting an Error, but a Notice.

Although this is acceptable since PHP is a dynamic language, you can prevent it with isset():

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

UPDATE

Per the comments, list() is the culprit for the Notice. In which case, I wouldn't recommend the use of list() when explode() doesn't yield the appropriate number of parameters.

If you must, the answer by brady or undefined offset when using php explode() can work. Although it's pretty ugly in my opinion. I believe your code would be much more intuitive if you just did the following:

$name = explode(' ', $queryString);if (isset($name[1])) {  // show lastname}else {  // show firstname}