<?php

$foo = new StdClass();

$foo->this_is_false = 0;

echo ($foo->this_is_false == "Dog+Breath"); // 1?

Is this some VERY radical type coercion going on here?

It's because you're adding string to an integer, so the string is cast to integer, and...

php > $foo = (integer) "Dog+Breath";
php > echo $foo;
0

    dalecosp radical

    Just php (and mysql). A loose comparison casts the string to a number and since the string doesn't start with any numerical characters, it ends up being a zero, which matches the assigned zero. You would need to use a strict === comparison for this to produce the expected result.

      PS: And the echo is casting the resulting Boolean true to a string value of "1".

      php > $foo = true;
      php > $bar = (string) $foo;
      php > var_export($bar);
      '1'
      
        a year later

        For anyone coming across this now: this is the old behaviour; starting with PHP 8 this will not output anything. (More accurately, the == test on the last line will now evaluate to false because 0 is no longer equal to "Dog+Breath" and that false value would be cast to an empty string for output.)

        Previously, as noted by pbismad, "integer==string" comparisons were handled by first casting the string to an integer. But as illustrated here, that led to weird and surprising results. Now, effectively, the comparison is made by first converting the integer to a string.

          a month later

          Maybe so, most likely I was careful with the data submitted, rather than the code checks...

          The further away I get from daily coding, the less I remember about the exact cases that led to the posts here....

            Write a Reply...