I have the following code:
<?php
$val = 0;
$res = $val == 'true';
var_dump($res);
?>
I always was under impression that $res should be ‘false’ as in the above expression PHP would try to type cast $val to boolean type (where zero will be converted as false) and a string (non-empty string is true). But if I execute the code above output will be:
boolean true
Am I missing something? Thanks.
In PHP, all non-empty, non-numeric strings evaluate to zero, so
0 == 'true'is TRUE, but0 === 'true'is FALSE. The stringtruehas not been cast to a boolean value, but is being compared as a string to the zero. The zero is left as an int value, rather than cast as a boolean. So ultimately you get:Try this:
Review the PHP type comparisons table. In general, when doing boolean comparisons in PHP and types are not the same (int to string in this case), it is valuable to use strict comparisons.