0

The array resAlloc contains 10 columns and 5 rows. All entries are equal to 0. So, I expect the following IF statement be TRUE, but it's false for some reason... Why?

if ($resAlloc[$i][$j] != 'ts' && $resAlloc[$i][$j] != 't' && $resAlloc[$i][$j] != 'st') {
    $count++;
}
0

3 Answers 3

3

!= evaluates 0 as false. Use !== which is more strict.

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

5 Comments

How does that explain the problem? 0!='ts' and false!='ts' should both evaluate to true, and so the if statement as a whole should be true.
Right, but I don't understand why any of the comparisons would evaluate to false just based on the fact that != treats 0 as false. ... Oh, this is an issue of order of operations, isn't it? The OP probably wanted the three != comparisons to be evaluated before the && operations, and that's probably not what's happening.
There's a completely separate issue, which is that 0 != 'any string' also evaluates to false (see my answer below).
I don't think you were downvoted. I upvoted you for a minute and then removed the upvote when I realized that I didn't understand your answer, and then I did comment. I'll upvote you again if one of us manages to straighten me out.
Sorry about the serial commenting; I should have added that the problem I mentioned actually would be addressed by your suggestion to use strict comparison. And they're kind of the same problem after all.
0

IIRC anything equaling 0 with != will return FALSE.

2 Comments

That's not correct. 0!=1 returns true (thank heavens!). I think this is an issue with comparing strings to integers -- strings get cast to the integer zero, so the two end up being equal after all!
I said IIRC, wasn't sure exactly.
0

The problem is that you're comparing a string and an integer, and PHP is "helpfully" casting the string to an integer -- the integer zero. 0!='ts' evaluates as false, because the comparison it ends up doing after conversion is 0!=0. You can prevent this by explicitly treating the contents of your array as a string:

strval($resAlloc[$i][$j]) != 'ts'

This will do the comparison '0'!='ts', which correctly evaluates to true. If you pass strval() a string it returns it unchanged, so this should be safe to use regardless of what's in your array.

Alternately, as Samy Dindane said, you can just use !== which won't do any type conversion.

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.