undefined offset PHP error

2019-01-01 13:37发布

问题:

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?

回答1:

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;
    }
}


回答2:

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.



回答3:

Undefined offset error in PHP is Like \'ArrayIndexOutOfBoundException\' in Java.

example:

<?php
$arr=array(\'Hello\',\'world\');//(0=>Hello,1=>world)
echo $arr[2];
?>

error: Undefined offset 2

It means you\'re referring to an array key that doesn\'t exist. \"Offset\" refers to the integer key of a numeric array, and \"index\" refers to the string key of an associative array.



回答4:

Undefined offset means there\'s an empty array key for example:

$a = array(\'Felix\',\'Jon\',\'Java\');

// This will result in an \"Undefined offset\" because the size of the array
// is three (3), thus, 0,1,2 without 3
echo $a[3];

You can solve the problem using a loop (while):

$i = 0;
while ($row = mysqli_fetch_assoc($result)) {
    // Increase count by 1, thus, $i=1
    $i++;

    $groupname[$i] = base64_decode(base64_decode($row[\'groupname\']));

    // Set the first position of the array to null or empty
    $groupname[0] = \"\";
}