数组检查未定义的偏移量PHP [英] Array check undefined offset php
问题描述
我会尽力解释.
我有一个array
:
$arrayTime = array(0=>"07",1=>"09", 3=>"13", 4=>"15", 5=>"17", 6=>"19");
在这里您可以看到未定义offset 2
现在我需要for
我的array
并在offset 2
上按下数字0(例如)
我试过使用这个:
Here you can see that is not defined offset 2
and now i need for
my array
and on offset 2
push number 0(for example)
I tried use this:
if($arrayTime[$i]==""){
$arrayTime[$i]=0;
}
是的,但是50至50 array
看起来像这样:
Yes it works but 50 to 50 array
looks like this:
$arrayTime = array(0=>"07",1=>"09", 3=>"13", 4=>"15", 5=>"17", 6=>"19",2=>"0");
但在if
所在的行上会引发错误:
but on the line where is the if
it throws an error:
注意:未定义的偏移量:第10行的C:\ wamp \ www \ xxx.php中的2
Notice: Undefined offset: 2 in C:\wamp\www\xxx.php on line 10
所以我需要相同的结果,但没有错误. 谢谢大家的帮助:)
So i need same result, but without error. Thanks for your help all :)
推荐答案
首先,它不会引发错误.它会警告您代码中可能存在错误.
First of all, it doesn't throw an error. It gives you a warning about a possible bug in your code.
if($arrayTime[$i]==""){}
这会尝试访问 $arrayTime[$i]
来检索一个值,以与您的空字符串进行比较.
This attempts to access $arrayTime[$i]
to retrieve a value to compare against your empty string.
尝试读取 并 使用不存在的数组索引以获取比较值是之所以会发出警告,是因为这通常是意外的.当键不存在时,使用null
代替,代码继续执行.
The attempt to read and use a non-existing array index to get a value for comparison is the reason why it throws the warning as this is usually unexpected. When the key does not exist null
is used instead and the code continues executing.
if(null == ""){} // this evaluates to true.
由于您要与空字符串""
进行比较,因此您的答案将是empty()
:
Because you are comparing against an empty string ""
, your answer would be empty()
:
if(empty($arrayTime[$i])){}
这意味着您期望键不存在,同时您正在检查值是否为空.请参阅类型比较表,以了解什么是什么以及什么不被视为空"
It means you are expecting a key not to exist and at the same time you are checking the value for emptyness. See the type comparison table to see what is and what is not considered 'empty'.
相同的规则适用于isset()
和is_null()
,如果密钥不存在,它将不会发出通知.因此,请选择最能满足您需求的功能.
The same rules apply to isset()
and is_null()
, it wont throw the notice if the key does not exist. So choose function that best serves your needs.
请记住,通过使用这些函数中的任何一个,您正在检查 value 和 not (如果数组中存在 key )不是.您可以为此使用 array_key_exists()
.
Keep in mind that by using any of these functions you are checking the value and not if the key exists in the array. You can use array_key_exists()
for that.
if(array_key_exists($i, $arrayTime)){}
这篇关于数组检查未定义的偏移量PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!