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"?

5
  • Reading it back, the title of the question seems very misleading, but i'm not sure what to title it. Commented Oct 17, 2017 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. Commented Oct 17, 2017 at 18:55
  • 2
    Possible duplicate of php not equal to != and !== Commented Oct 17, 2017 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 Commented Oct 17, 2017 at 19:00
  • Possible duplicate of PHP String - int comparison Commented Oct 17, 2017 at 19:09

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

0 is also a false-y value. I think it's using that more than using casting the letter to an int.
I wouldn't have answered had I seen this answer, thank you @Unamata Sanatarai. Great answer!
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.