Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How can you easily avoid getting this error/notice:

Notice: Undefined offset: 1 in /var/www/page.php on line 149

... in this code:

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

There are not always two values returned by explode, but if you want to use list() how can you then easily avoid the notice?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
324 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...