Last active
June 15, 2016 19:36
-
-
Save lsloan/b348053bbefd2ffec01c90455cbde8fd to your computer and use it in GitHub Desktop.
PHP: Avoid the equal ("==") comparison operator for comparing strings that may be numeric.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* When using the equal comparison operator ("==") to compare a number with a string or | |
* the comparison involves numeric strings, 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 using the identical comparison operator | |
* ("===") as that involves comparing the type as well as the value. | |
* | |
* It's safer to always use strcmp() or the identical comparison operator ("===") for | |
* string comparisons. | |
* | |
* Based on PHP documentation at: http://php.net/manual/en/language.operators.comparison.php | |
*/ | |
test("1234", "1234"); | |
test("1234", " 1234"); | |
test("1234", "\n1234"); | |
test("1234", "1234 "); | |
test("1234", "1234\n"); | |
function test($x, $y) { | |
echo var_dump_str($x) . ' vs. '; | |
echo var_dump_str(show_cr($y)) . PHP_EOL; | |
$strcmpTest = (strcmp($x, $y) == 0); | |
$equalTest = ($x == $y); | |
$identicalTest = ($x === $y); | |
echo 'strcmp() test: ' . var_export($strcmpTest, true) . PHP_EOL; | |
echo 'equal test: ' . var_export($equalTest, true) . ' ' . | |
(($equalTest == $strcmpTest) ? 'AGREE' : 'DISAGREE') . PHP_EOL; | |
echo 'identical test: ' . var_export($identicalTest, true) . ' ' . | |
(($identicalTest == $strcmpTest) ? 'AGREE' : 'DISAGREE') . PHP_EOL; | |
echo PHP_EOL; | |
} | |
function show_cr($var) { | |
return str_replace("\n", "\\n", $var); | |
} | |
function var_dump_str($var) { | |
ob_start(); | |
var_dump($var); | |
$dump = trim(ob_get_contents()); | |
ob_end_clean(); | |
return $dump; | |
} | |
/* | |
* Results: | |
* | |
* string(4) "1234" vs. string(4) "1234" | |
* strcmp() test: true | |
* equal test: true AGREE | |
* identical test: true AGREE | |
* | |
* string(4) "1234" vs. string(5) " 1234" | |
* strcmp() test: false | |
* equal test: true DISAGREE | |
* identical test: false AGREE | |
* | |
* string(4) "1234" vs. string(6) "\n1234" | |
* strcmp() test: false | |
* equal test: true DISAGREE | |
* identical test: false AGREE | |
* | |
* string(4) "1234" vs. string(5) "1234 " | |
* strcmp() test: false | |
* equal test: false AGREE | |
* identical test: false AGREE | |
* | |
* string(4) "1234" vs. string(6) "1234\n" | |
* strcmp() test: false | |
* equal test: false AGREE | |
* identical test: false AGREE | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment