1

A friend of mine recently showed my the following snippet

<?php
    $a = 0;
    $b = 'x';
    if(FALSE == $a && $a == $b && $b == TRUE) {
         echo 'WTF!?';
    }
?>

which ouputs WTF!?

I understand why FALSE == $a holds, because zero is considered to be FALSE. I also understand why $b == TRUE holds, because the string is not empty. But I didn't understand why $a == $b is true, could somebody explain to me what type coercion rules play together here to get this rather amusing result?

kamal pal
  • 4,187
  • 5
  • 25
  • 40
wastl
  • 2,643
  • 14
  • 27

1 Answers1

4

when you compare $a == $b you are comparing an int with a string so PHP tries to parse the string into an int if it fails which happened in this case, it changes its value to 0 and then 0 == 0 returns true. Check this:

If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically. These rules also apply to the switch statement. The type conversion does not take place when the comparison is === or !== as this involves comparing the type as well as the value.

Change this condition $a == $b to $a === $b to compare the type as well. Hope this helps.

Osama Sayed
  • 1,993
  • 15
  • 15