7

I don't understand below output . found below expressions on php.net manual in boolean section.

<?php

    var_dump(0 == 'all');//   IS bool(true)
    var_dump((string)0 == 'all');  //IS bool(false)
    var_dump(0 === 'all'); // //IS bool(false)

?>
Rizier123
  • 58,877
  • 16
  • 101
  • 156
ajax D
  • 133
  • 7
  • 8
    A gotcha of PHP type juggling http://php.net/manual/en/language.operators.comparison.php – DhruvPathak Dec 30 '14 at 10:43
  • 6
    `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.` – Charlotte Dunois Dec 30 '14 at 10:45
  • 1
    try `var_dump((integer)'all');` and `var_dump((integer)'32all 0');` and i think you will understand – Forien Dec 30 '14 at 10:55
  • 1
    That was already asked in SO: http://stackoverflow.com/questions/672040/comparing-string-to-integer-gives-strange-results – javier_domenech Dec 30 '14 at 10:56
  • 3
    possible duplicate of [Comparing String to Integer gives strange results](http://stackoverflow.com/questions/672040/comparing-string-to-integer-gives-strange-results) – Niels Keurentjes Dec 30 '14 at 10:56

1 Answers1

8

If you compare an integer with a string, each string is converted to a number, so:

(0 == 'all') -> (0 == 0) -> true

The type conversion does not happen when the comparison is === or !== because this also includes the comparison of the type:

(0 === 'all') -> (integer == string) -> false

The second line of code you wrote force the integer value to be considered as a string, and so the numerical cast doesn't happen.

Giulio Biagini
  • 935
  • 5
  • 8
  • 1
    `(integer == string)` Think you forgot a `=` – Rizier123 Dec 30 '14 at 10:55
  • 1
    @Rizier123 not really, because `integer == string` is written as pseudo-code and logically is always false. He wrote it like that so casuals can understand difference between `==` which compare values to `===` which compare values **and** types. – Forien Dec 30 '14 at 10:58
  • The code I wrote should be considered as _pseudo code_, and so, it doesn't matter how many `=` occurs between the `->` and the `<-` chars. – Giulio Biagini Dec 30 '14 at 11:05