How to avoid undefined offset

后端 未结 8 2194
梦谈多话
梦谈多话 2020-12-13 05:24

How can you easily avoid getting this error/notice:

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

... in this code:

8条回答
  •  Happy的楠姐
    2020-12-13 06:21

    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.

提交回复
热议问题