How to avoid undefined offset

Viewed 30731

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?

8 Answers

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;
}
Related