51

我在 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
}

错误是什么意思?

4

4 回答 4

44

如果preg_match没有找到匹配项,$matches则为空数组。因此,您应该preg_match在访问之前检查是否找到匹配项$matches[0],例如:

function get_match($regex,$content)
{
    if (preg_match($regex,$content,$matches)) {
        return $matches[0];
    } else {
        return null;
    }
}
于 2010-03-24T14:05:37.397 回答
38

如何在 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

如果键存在,则获取值,如果不存在,则无需查询其值。

于 2014-02-15T04:28:50.400 回答
5

PHP 中的未定义偏移错误类似于Java 中的“ArrayIndexOutOfBoundException”

例子:

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

错误:未定义的偏移量 2

这意味着您指的是不存在的数组键。“偏移”是指数字数组的整数键,“索引”是指关联数组的字符串键。

于 2015-01-25T13:12:37.577 回答
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] = "";
}
于 2016-06-10T22:06:57.150 回答