未定义偏移 PHP 错误
我在 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
}
该错误是什么意思?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果
preg_match
未找到匹配项,则$matches
为一个空数组。因此,您应该在访问$matches[0]
之前检查preg_match
是否找到匹配项,例如:If
preg_match
did not find a match,$matches
is an empty array. So you should check ifpreg_match
found an match before accessing$matches[0]
, for example:如何在 PHP 中重现此错误:
创建一个空数组并询问给定键的值,如下所示:
发生了什么?
您要求数组提供给定的值它不包含的密钥。它会给你值 NULL,然后将上述错误放入错误日志中。
它在数组中查找您的密钥,并发现
未定义
。如何让错误不发生?
在询问键值之前先询问键是否存在。
如果key存在,则获取value,如果不存在,则无需查询其value。
How to reproduce this error in PHP:
Create an empty array and ask for the value given a key like this:
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.
If the key exists, then get the value, if it doesn't exist, no need to query for its value.
PHP 中未定义的偏移量错误就像 Java 中的 'ArrayIndexOutOfBoundException' 一样。
示例:
error: Undefined offset 2
这意味着您引用的数组键不存在。 “抵消”
指的是数值数组的整数键,“索引”指的是
关联数组的字符串键。
Undefined offset error in PHP is Like 'ArrayIndexOutOfBoundException' in Java.
example:
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.
未定义的偏移意味着有一个空数组键,例如:
您可以使用循环(while)解决问题:
Undefined offset means there's an empty array key for example:
You can solve the problem using a loop (while):