Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

undefined offset PHP error

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?

like image 748
user272899 Avatar asked Mar 24 '10 14:03

user272899


2 Answers

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;     } } 
like image 125
Gumbo Avatar answered Sep 28 '22 23:09

Gumbo


How to reproduce this error in PHP:

Create an empty array and ask for the value given a key like this:

php> $foobar = array();  php> echo gettype($foobar); array  php> echo $foobar[0];  PHP Notice:  Undefined offset: 0 in  /usr/local/lib/python2.7/dist-packages/phpsh/phpsh.php(578) :  eval()'d code on line 1 

What happened?

You asked an array to give you the value given a key that it does not contain. It will give you the value NULL then put the above error in the errorlog.

It looked for your key in the array, and found undefined.

How to make the error not happen?

Ask if the key exists first before you go asking for its value.

php> echo array_key_exists(0, $foobar) == false; 1 

If the key exists, then get the value, if it doesn't exist, no need to query for its value.

like image 34
Eric Leschinski Avatar answered Sep 29 '22 01:09

Eric Leschinski