对于此代码:
<?php
$data = array('0' => 'A_VALUE');
foreach ($data as $key => $value) {
if ($key == "Something to match the key on") {
print_r($key);
print_r('key matches');
}
}
Run Code Online (Sandbox Code Playgroud)
我得到了这个输出
0键匹配
在线示例:http://3v4l.org/dKOWq#v431
我不能为我的生活弄清楚为什么我得到这个.比较应明确返回FALSE.
谁可以给我解释一下这个?
谁可以给我解释一下这个?
类型杂耍.
由于您正在使用==,PHP将0(int)与Something to match the key on(字符串)进行比较.双方都投了一个int.所以Something to match the key on成为0.而0 == 0为true.
使用严格相等或显式转换.
例如:
if ((string)$key == (string)"Something to match the key on") {
// code
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
100 次 |
| 最近记录: |