Foreach循环问题在PHP中 [英] Foreach loop issues in php
问题描述
这里有一些我有的代码:(p只是回声加上一个换行符)
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ => $ reqInfo)
{
p($ k);
if('van'== $ k){p('The key is the van,continue');继续; } //如果我们到达数组的部分,那么van就是key
// do stuff
}
我得到这个输出:
$ $ $ $ $ $ $ $ $ $ $ $ $关键是面包车,继续
1
2
3
van
关键是面包车,继续
为什么当key是0时if语句返回true?这个foreach循环处理的是当键== 0(除了键是'van'之外的任何其他键)时应用的逻辑,并且这会弄乱逻辑,因为当键是0时它返回true。
任何帮助?
谢谢。
使用 ===
进行比较。当PHP比较字符串和整数时,首先将字符串转换为整数值,然后进行比较。
请参见比较运算符。
Here is some code I have: (p just echos plus adds a newline)
foreach ($vanSteps as $k => $reqInfo)
{
p($k);
if ('van' == $k) { p('The key is the van, continue'); continue; }//continue if we reached the part of the array where van is key
//do stuff
}
and I'm getting this output:
0
The key is the van, continue
1
2
3
van
The key is the van, continue
Why does the if statement return true when the key is 0? This foreach loop handles logic that applies when the key == 0 (and any other key except if the key is 'van') and this messes up the logic because it's return true when key is 0.
Any help?
Thank you.
Use ===
for this comparison. When PHP compares string and integer it first casts string to integer value and then does comparison.
See Comparison Operators in manual.
这篇关于Foreach循环问题在PHP中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!