PHP Notice: Undefined offset: 2

I’m using this code to embed Gists in WordPress. It works fine, Gists show up, but I keep getting an error in my debug.log file:
PHP Notice: Undefined offset: 2 in /functions.php on line 333

(line 333 is esc_attr($matches[2]))

    wp_embed_register_handler( 'gist', '/https?://gist.github.com/([a-z0-9]+)(?file=.*)?/i', 'embed_handler_gist' );

function embed_handler_gist( $matches, $attr, $url, $rawattr ) {

    $embed = sprintf(
            '<script src="https://gist.github.com/%1$s.js%2$s"></script>',
            esc_attr($matches[1]),
            esc_attr($matches[2])
            );

    return apply_filters( 'embed_gist', $embed, $matches, $attr, $url, $rawattr );

}

Related posts

2 comments

  1. That error simply means that $matches[2] doesn’t exist. You can avoid this error by checking for its existence before attempting to access the variable.

    if( isset($matches[2]) )
        esc_attr($matches[2]);
    

    or if you are looking to assign a default value:

    $value = isset($matches[2]) ? $matches[2] : false;
    

    isset()

  2. I ran into an offset issue when I was trying to pull a media list from a mysql database. When I had only one entry in the database it gave me an offset error. Check to see if you have both variables returned. If you only get one, maybe you can program an error check with an sizeof($array) or count($array). Just a thought 🙂

Comments are closed.