Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparison Operator - Type Juggling and Booleans

Tags:

php

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

like image 523
IsisCode Avatar asked Jan 30 '12 15:01

IsisCode


3 Answers

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).

like image 179
Justin ᚅᚔᚈᚄᚒᚔ Avatar answered Sep 27 '22 21:09

Justin ᚅᚔᚈᚄᚒᚔ


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.

like image 24
Jon Avatar answered Sep 27 '22 20:09

Jon


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.

like image 38
Dunhamzzz Avatar answered Sep 27 '22 20:09

Dunhamzzz