Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

foreach, unexpected result for element, which key is 0

I have this code

$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> ';
    }
}

Its surprise, for first element "0"=>"http://site.com/somepage/param1/param2/0", not created link, (for other elements works fine)

If replace first element key 0 on something other, for example 4, now links created. What is wrong ?

like image 933
Oto Shavadze Avatar asked Feb 02 '26 08:02

Oto Shavadze


1 Answers

This is happening because 0 == "thispage" and the first key is 0. To find out more about this, take a look at the PHP manual page about Type Juggling.

Use === ("is identical to") instead of == ("is equal to"), because 0 is equal to "thispage", but not identical.

This is what happens with ==:

  • $key takes the integer value of 0
  • PHP tries to compare 0 == "thispage"
  • in order to make the comparison, it needs to cast "thispage" to integer
  • the resulting comparison is 0 == 0, which is true

If you use ===:

  • $key takes the integer value of 0
  • PHP tries to compare 0 === "thispage"
  • since 0 is of a different type (integer) than "thispage" (string), the result is false
like image 151
rid Avatar answered Feb 03 '26 21:02

rid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!