undefined offset PHP error

user272899 picture user272899 · Mar 24, 2010 · Viewed 337.8k times · Source

I am receiving the following error in PHP

Notice undefined offset 1: in C:\wamp\www\includes\imdbgrabber.php line 36

Here is the PHP code that causes it:

<?php

# ...

function get_match($regex, $content)  
{  
    preg_match($regex,$content,$matches);     

    return $matches[1]; // ERROR HAPPENS HERE
}

What does the error mean?

Answer

Gumbo picture Gumbo · Mar 24, 2010

If preg_match did not find a match, $matches is an empty array. So you should check if preg_match found an match before accessing $matches[0], for example:

function get_match($regex,$content)
{
    if (preg_match($regex,$content,$matches)) {
        return $matches[0];
    } else {
        return null;
    }
}