未定义偏移量的PHP错误

53

我在PHP中收到以下错误:

注意:未定义的偏移量1:位于C:\wamp\www\includes\imdbgrabber.php第36行

以下是导致该错误的PHP代码:

<?php

# ...

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

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

这个错误的意思是什么?


当我使用:$url = 'http://www.imdb.com/title/tt0367882/';它会显示该标题的电影信息。当我使用 $url = $_GET['link'];它不会显示数据。 - user272899
4个回答

45
如果 preg_match 没有找到匹配项,$matches 将是一个空数组。所以在访问 $matches[0] 之前,应该检查 preg_match 是否找到了匹配项,例如:
function get_match($regex,$content)
{
    if (preg_match($regex,$content,$matches)) {
        return $matches[0];
    } else {
        return null;
    }
}

那个错误已经被修复了。但我仍然无法弄清楚为什么当我使用:$url = $_GET['link'];时它不会显示电影信息,只有当我使用:$url = 'http://www.imdb.com/title/tt0367882/';时才会显示。我已经用echo测试了变量中获取的正确数据,但它仍然无法工作。 - user272899
2
else块不是必需的,因为该函数无论如何都会自动返回NULL - Amal Murali

40

如何在PHP中重现此错误:

创建一个空数组,并像这样请求给定键的值:

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

发生了什么?

您要求数组根据一个不存在的键来给您提供值。它将返回值NULL,然后将以上错误记录在错误日志中。

它在数组中查找您的键,并发现undefined

如何避免这个错误?

在获取值之前先询问该键是否存在。

php> echo array_key_exists(0, $foobar) == false;
1
如果键存在,则获取其对应的值,如果不存在,则无需查询其值。

我在我的Magento 2.3网站中遇到了未定义的偏移错误,https://magento.stackexchange.com/q/321321/57334。感谢任何帮助。 - zus

5

在 PHP 中出现“Undefined offset”错误类似于 Java 中的“ArrayIndexOutOfBoundException”。

例子:

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

错误:未定义的偏移量2

这意味着您正在引用不存在的数组键。"偏移量"是指数字数组的整数键,而"索引"是指关联数组的字符串键。


你让我看到了新世界!谢谢。 - Deepak Keynes

1

未定义的偏移量意味着存在一个空的数组键,例如:

$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];

你可以使用循环(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] = "";
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接