字符串比较的行为不同
$x = array(3) {
[0]=> "A - 1"
[1]=> "B - 4"
["Total"]=> "5"
}
尝试:
foreach($x as $k=>$v){
if($k=="Total"){break;}
echo $v."<br>";
}
因为我只想输出 :
A - 1
B - 4
但我在输出中没有看到任何内容。
我做错了什么?
谢谢
$x = array(3) {
[0]=> "A - 1"
[1]=> "B - 4"
["Total"]=> "5"
}
TRY:
foreach($x as $k=>$v){
if($k=="Total"){break;}
echo $v."<br>";
}
Because I just want to output :
A - 1
B - 4
But I don't see anything in the output.
what do I wrong?
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当你第一次跳出循环时,你在输出中什么也得不到。
在第一次迭代中,将数值
0
的$k
与字符串"Total"
进行比较,此比较返回true
因为 PHP 会在比较之前将字符串"total"
转换为数字,而"total"
转换为数字时为0
。Ideone
要解决此问题,请不要使用
==
,而是使用strcmp
相反,它会在比较之前将数字键转换为字符串,或者您可以使用===
来检查类型和值。Ideone
You get nothing in the output as you break out of the loop the very fist time.
In the first iteration
$k
with value0
which is numeric is compared with"Total"
which is a string and this comparison returnstrue
because PHP will convert the string"total"
to a number before comparison and"total"
when converted to number is0
.Ideone
To fix this don't use
==
, usestrcmp
instead which will convert the numeric keys to string before comparison or you can use===
which checks type as well as value.Ideone
将
echo $v."
放在 else 语句中......";
Put
echo $v."<br>";
in an else statement......