How to avoid undefined offset

后端 未结 8 2207
梦谈多话
梦谈多话 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:22

    I often come across this issue, so I wanted a function that allowed something nicer syntactically without unnecessarily padding the array or string.

    // Put array entries in variables. Undefined index defaults to null
    function toVars($arr, &...$ret)
    {
        $n = count($arr);
        foreach ($ret as $i => &$r) {
            $r = $i < $n ? $arr[$i] : null;
        }
    }
    
    // Example usage
    toVars(explode('|', $value), $func, $field);
    

    For my purposes, I'm usually working with an array, but you could write a similar function that includes the explode function, like this...

    // Explode and put entries in variables. Undefined index defaults to null
    function explodeTo($delimiter, $s, &...$ret)
    {
        $arr = explode($delimier, $s);
        $n = count($arr);
        foreach ($ret as $i => &$r) {
            $r = $i < $n ? $arr[$i] : null;
        }
    }
    
    // Example usage
    toVars('|', $value, $func, $field);
    

    Requires PHP5.6 or above for variadic function: http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list

提交回复
热议问题