1

I will keep this brief, this is my code:

<?php

$arr = array(
    1,
    2,
    3,
    "x" => "aaa", 
    "y" => "bbb"
);

foreach($arr as $k => $v){

    if($k !="y" && $k != "x") {
        echo $v . " ";
    }

}

?>

and this is the result:

2 3

and it acts as though this:

$example = 0;
if ($example == 'x' || $example == 'y') {
    echo "true";
}

would echo out "true" instead of nothing.


Basically, my question is: why does it skip echo-ing out the first element of the array, if 0 does not equal "x" or "y"?

aakk
  • 334
  • 4
  • 15
  • Reading it back, the title of the question seems very misleading, but i'm not sure what to title it. – aakk Oct 17 '17 at 18:54
  • 3
    It's an issue with `!=` being more lenient than `!==` because of the `0` value of the key. Try the latter, and you'll get what you're looking for. – aynber Oct 17 '17 at 18:55
  • 2
    Possible duplicate of [php not equal to != and !==](https://stackoverflow.com/questions/3641819/php-not-equal-to-and) – aynber Oct 17 '17 at 18:59
  • @aynber Yes, I think it is, but I wasn't sure where the problem was before asking the question, now that I know, I would agree with you – aakk Oct 17 '17 at 19:00
  • Possible duplicate of [PHP String - int comparison](https://stackoverflow.com/questions/9468148/php-string-int-comparison) – simon.ro Oct 17 '17 at 19:09

2 Answers2

4

The == sorts out the types for you.

0 is an int, so it is going to cast y and x to an int. Which is not parseable as one, and will become 0. A string '0x' would become 0, and would match!

Go with !==

http://sandbox.onlinephpfunctions.com/code/bed936181e386ddfe75e4ef92771bf61ad2e7915

<?php

$arr = array(
    1,
    2,
    3,
    "x" => "aaa", 
    "y" => "bbb"
);

foreach($arr as $k => $v){

    if($k !=="y" && $k !== "x") {
        echo $v . " ";
    }

}
// result:
// 1 2 3 

source

Unamata Sanatarai
  • 6,475
  • 3
  • 29
  • 51
  • 1
    `0` is also a false-y value. I think it's using that more than using casting the letter to an int. – aynber Oct 17 '17 at 18:59
  • I wouldn't have answered had I seen this answer, thank you @Unamata Sanatarai. Great answer! – Ingo Oct 17 '17 at 19:29
2

That is a good one, I think I found the fix, instead of using != in both of your evaluations in the if statement, try using !== so, change your if statement to:

if($k !== "y" && $k !== "x")

See Unamata Sanatarai answer above, explained very well.

Ingo
  • 116
  • 9