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?
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; } }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With