foreach,元素的意外结果,哪个键为0

OTA*_*TAR 2 php arrays foreach

我有这个代码

$arr = array(
    "0"=>"http://site.com/somepage/param1/param2/0",
    "1"=>"http://site.com/somepage/param1/param2/1",
    "thispage" => "http://site.com/somepage/param1/param2/2",
    "3"=> "http://site.com/somepage/param1/param2/3"
);



foreach ($arr as $k=>$v) {
    if ($k == "thispage") {
        echo $k." ";
    }
    else {
        echo '<a href="'.$v.'">'.$k.'</a> ';
    }
}
Run Code Online (Sandbox Code Playgroud)

令人惊讶的是,第一个元素"0"=>"http://site.com/somepage/param1/param2/0",没有创建链接,(其他元素工作正常)

如果替换其他内容的第一个元素键0,例如4,现在创建链接.怎么了 ?

rid*_*rid 5

发生这种情况是因为0 == "thispage"第一个关键是0.要了解更多相关信息,请查看有关Type Juggling的PHP手册页.

使用===("等同于"),而不是==("等于"),因为0等于"thispage",但不完全相同.

这是发生的事情==:

  • $keyinteger的值0
  • PHP试图比较 0 == "thispage"
  • 为了作出比较,它需要投"thispage"integer
  • 结果比较是0 == 0,true

如果您使用===:

  • $keyinteger的值0
  • PHP试图比较 0 === "thispage"
  • 因为0是(integer)而不是"thispage"(string),结果是false