use*_*899 42 php undefined offset
我在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
}
Run Code Online (Sandbox Code Playgroud)
错误是什么意思?
Gum*_*mbo 38
如果preg_match没找到匹配,$matches则为空数组.因此,您应该preg_match在访问之前检查是否找到匹配项$matches[0],例如:
function get_match($regex,$content)
{
if (preg_match($regex,$content,$matches)) {
return $matches[0];
} else {
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
Eri*_*ski 31
如何在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
Run Code Online (Sandbox Code Playgroud)
发生了什么?
您要求一个数组给出给定一个它不包含的键的值.它将为您提供NULL值,然后将上述错误放在errorlog中.
它在数组中寻找你的密钥,然后找到了undefined.
如何使错误不发生?
在询问密钥之前,先询问密钥是否存在.
php> echo array_key_exists(0, $foobar) == false;
1
Run Code Online (Sandbox Code Playgroud)
如果密钥存在,则获取值,如果该值不存在,则无需查询其值.
PHP 中的未定义偏移错误就像Java 中的'ArrayIndexOutOfBoundException'。
例子:
<?php
$arr=array('Hello','world');//(0=>Hello,1=>world)
echo $arr[2];
?>
Run Code Online (Sandbox Code Playgroud)
错误:未定义的偏移量 2
这意味着您指的是一个不存在的数组键。“偏移量”指的是数值数组的整数键,“索引”指的是关联数组的字符串键。
| 归档时间: |
|
| 查看次数: |
303536 次 |
| 最近记录: |