How to avoid undefined offset

list($func, $field) = array_pad(explode('|', $value, 2), 2, null);

Two changes:

  • It limits the size of the array returned by explode() to 2. It seems, that no more than this is wanted
  • If there are fewer than two values returned, it appends null until the array contains 2 values. See Manual: array_pad() for further information

This means, if there is no | in $value, $field === null. Of course you can use every value you like to define as default for $field (instead of null). Its also possible to swap the behavior of $func and $field

list($func, $field) = array_pad(explode('|', $value, 2), -2, null);

Now $func is null, when there is no | in $value.


I don't know of a direct way to do this that also preserves the convenience of

list($func, $field) = explode('|', $value);

However, since it's really a pity not to be able to do this, you may want to consider a sneaky indirect approach:

list($func, $field) = explode('|', $value.'|');

I have appended to $value as many |s as needed to make sure that explode will produce at least 2 items in the array. For n variables, add n-1 delimiter characters.

This way you won't get any errors, you keep the convenient list assignment, and any values which did not exist in the input will be set to the empty string. For the majority of cases, the latter should not give you any problems so the above idea would work.


This worked for me:

@list($func, $field) = explode('|', $value);

You get an undefined offset when the thing you're trying to explode the string by ($value) doesn't actually have it in, I believe.

This question is very much similar to this: undefined offset when using php explode(), where there is a much further explanation which should fully solve your issue.

As for checking for the occurrence of '|' as to prevent the error, you can do:

$pos = strpos($value,'|');

if(!($pos === false)) {
     //$value does contain at least one |
}

Hope this helps.


I'd probably break this up into two steps

$split = explode('|', $value);
$func = $split[0];
if(count($split) > 1)
  $field = $split[1];
else
  $field = NULL;

There's probably a quicker and neater way though.