UPDATE (2/17/2022): String-to-number loose comparisons have changed with the release of PHP 8.0. See https://www.php.net/manual/en/migration80.incompatible.php for more information. The information below relates to PHP versions prior to PHP 8.0.
My ZCE studies didn’t expose me to these edge cases, well except for the first one.
If you use ==
watch out for these and related:
<?php
echo ((0 == 'hello') ? 'true' : 'false').PHP_EOL; //true
echo ((0 == '1hello') ? 'true' : 'false').PHP_EOL; //false
echo (('0' == '0e0') ? 'true' : 'false').PHP_EOL; //true
echo (('0' == '0e0e') ? 'true' : 'false').PHP_EOL; //false
echo (('0' == '0ee') ? 'true' : 'false').PHP_EOL; //false
echo ((0 == '0x0') ? 'true' : 'false').PHP_EOL; //true
echo ((0 == '0x0x') ? 'true' : 'false').PHP_EOL; //true
echo ((0 == '0x0b') ? 'true' : 'false').PHP_EOL; //false
?>
Whoa, we don’t want any of these to return true
, what’s a developer to do?
Strict comparisons with ===
<?php
echo ((0 === 'hello') ? 'true' : 'false').PHP_EOL; //false
echo ((0 === '1hello') ? 'true' : 'false').PHP_EOL; //false
echo (('0' === '0e0') ? 'true' : 'false').PHP_EOL; //false
echo (('0' === '0e0e') ? 'true' : 'false').PHP_EOL; //false
echo (('0' === '0ee') ? 'true' : 'false').PHP_EOL; //false
echo ((0 === '0x0') ? 'true' : 'false').PHP_EOL; //false
echo ((0 === '0x0x') ? 'true' : 'false').PHP_EOL; //false
echo ((0 === '0x0b') ? 'true' : 'false').PHP_EOL; //false
?>
Much better.
Learn more at http://php.net/manual/en/types.comparisons.php