How to avoid undefined offset

后端 未结 8 2183
梦谈多话
梦谈多话 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条回答
  • 2020-12-13 06:30

    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.

    0 讨论(0)
  • 2020-12-13 06:31

    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.

    0 讨论(0)
提交回复
热议问题