IsisCode
IsisCode

Reputation: 2490

Comparison Operator - Type Juggling and Booleans

I've been reading the PHP Docs on Type Juggling and Booleans but I still don't understand why this comparison evaluates as true. My [incorrect] understanding tells me that in the below if statement, the integer 0 is considered FALSE and "a", being a non-empty string is considered TRUE. Therefore, I expected this comparison to resolve to FALSE == TRUE and ultimately, FALSE. Which part did I get wrong?

   <?php
            if(0 == "a"){
                    $result = "TRUE";
            }else{
                    $result = "FALSE";
            }

            //$result == "TRUE"
    ?>

http://codepad.viper-7.com/EjxBF5

Upvotes: 5

Views: 218

Answers (3)

Justin ᚅᚔᚈᚄᚒᚔ
Justin ᚅᚔᚈᚄᚒᚔ

Reputation: 15369

When PHP does a string <=> integer comparison, it attempts to convert the string to a number in an intelligent way. The assumption is that if you have a string "42" then you want to compare the value 42 to the other integer. When the string doesn't start with numbers, then its value is zero.

From the docs:

The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero).

This behavior is also inferred in the comparison docs (look at the first line in the first example).

Upvotes: 9

Dunhamzzz
Dunhamzzz

Reputation: 14798

It will work if you use a strict comparison === instead of ==. The strict comparison also checks the type of the variables, so 0 === 'a' would be false.

Upvotes: 2

Jon
Jon

Reputation: 437336

Your mistake is that you assume operator == coerces each of its operands to boolean before comparing them. It does no such thing.

What happens is that since you are comparing an integer to a string, the string is converted to an integer (in this case "a" converts to 0) and then the comparison 0 == 0 is performed.

Upvotes: 4

Related Questions