Elvin
Elvin

Reputation: 367

Php undefined offset error

Running the following code:

        preg_match("/^top\-sites\-csv\_(.+)\_/i", $file, $matches);
    $site_id = $matches[1];

And it keeps generating this notice:

PHP Notice:  Undefined offset

I guess its happening when the regex does not find a match. problem is that the script is on a cron and my error log grows huge in no time and then needs manual cleaning..

Upvotes: 1

Views: 1410

Answers (2)

Ghostman
Ghostman

Reputation: 6114

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[1]

Upvotes: 0

oezi
oezi

Reputation: 51807

just check $matches using isset() before working with ist:

if(isset($matches[1])){
  $site_id = $matches[1];
  // do more here
}

Upvotes: 2

Related Questions