Klausos Klausos
Klausos Klausos

Reputation: 16050

PHP: If statement issue

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++;
}

Upvotes: 0

Views: 79

Answers (3)

octern
octern

Reputation: 4868

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.

Upvotes: 0

Samy Dindane
Samy Dindane

Reputation: 18706

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

Upvotes: 3

alexpja
alexpja

Reputation: 576

IIRC anything equaling 0 with != will return FALSE.

Upvotes: 0

Related Questions