【问题标题】:undefined offset PHP error未定义的偏移量PHP错误
【发布时间】:2011-01-31 06:45:04
【问题描述】:

我在 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 = 'imdb.com/title/tt0367882';它显示该标题的电影信息。当我使用 $url = $_GET['link'];它不显示数据

标签: php undefined offset


【解决方案1】:

如果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 = 'imdb.com/title/tt0367882';我已经测试过,我从变量中得到了正确的数据,我是,但它不起作用。
  • else 块不是必需的,因为无论如何该函数都会自动返回 NULL。
【解决方案2】:

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

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

【讨论】:

【解决方案3】:

PHP 中的未定义偏移错误类似于 Java 中的 'ArrayIndexOutOfBoundException'。

示例:

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

错误:未定义的偏移量 2

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

【讨论】:

  • 你让我大开眼界!谢谢
【解决方案4】:

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

$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] = "";
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多