How to avoid undefined offset

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

    Want to mention a more general utility function that I use since decades. It filters out empty values and trims spaces. It also uses array_pad() to make sure you get at least the requested amount of values (as suggested by @KingCrunch).

    /**
     * Does string splitting with cleanup.
     * Added array_pad() to prevent list() complaining about undefined index
     * @param $sep string
     * @param $str string
     * @param null $max
     * @return array
     */
    function trimExplode($sep, $str, $max = null)
    {
        if ($max) {
            $parts = explode($sep, $str, $max); // checked by isset so NULL makes it 0
        } else {
            $parts = explode($sep, $str);
        }
        $parts = array_map('trim', $parts);
        $parts = array_filter($parts);
        $parts = array_values($parts);
        $parts = array_pad($parts, $max, null);
        return $parts;
    }
    

提交回复
热议问题