0 Compare with any leading string that is not a number (or, in other words, a character that cannot be converted to a number) (operator is ==), all returns true.
The reason is that when comparing numbers with strings, first try to convert the string into a number, and then compare. If a string cannot be converted into a number, the conversion result is 0, so comparing with 0 always returns true.
In PHP, when two numeric strings (strings containing only numbers) are compared, they are directly converted into numerical values for comparison
The following example: (note $a and $ bThe last digit of the two variables is not equal)
Sample code:
<?php $a = '511203199106034578'; $b = '511203199106034579'; if ($a==$b) { echo 'equal'; } else { echo 'notEqual'; } ?>
Run the above program but found that the result is equal (not the result we thought) We put $a and $b Add a letter a respectively
<?php $a = 'a511203199106034578'; $b = 'a511203199106034579'; if ($a==$b) { echo 'equal'; } else { echo 'notEqual'; } ?>
This time the output is notEqual (the correct result)
Explanation: The above example is equal because PHP converts two numeric strings into numeric types , and these two numbers are exactly equal
<?php $a = 511203199106034578; $b = 511203199106034579; echo $a; // 输出 5.1120319910603E+17 即511203199106030000 echo $b; // 输出 5.1120319910603E+17 即511203199106030000 ?>
So the result we get in the example is equal
To avoid such unexpected results, use the type comparison operator === as in the following example (if $ a is equal to $b, and their types are also the same)
<?php $a = '511203199106034578'; $b = '511203199106034579'; if ($a===$b) { echo 'equal'; } else { echo 'notEqual'; } ?>
Explain with an example
<?php $str1 = "123456789012345678"; $str2 = "123456789012345679"; if($str1 == $str2){ echo "1.equal\n"; }esle{ echo "1.not equal\n"; } if($str1 === $str2){ echo "2.equal\n"; }esle{ echo "2.not equal\n"; } if(strcmp($st1, $str2)==0){ echo "3.equal\n"; }esle{ echo "3.not equal\n"; } if($str1 == $str2){ echo "1.equal\n"; }esle{ echo "1.not equal\n"; }
The result after running is quite strange:
1.equal
2.not equal
3.not equal
After checking the reason, when PHP compares two numeric strings, it will first treat the two strings as numbers. And store these two strings in scientific notation, which retains 16 decimal places. In other words, when storing, $str1=1.2345678901234567E+17; $str2=1.2345678901234567E+17. So it is judged that $str1==$str2. Different lengths, adding non-numeric characters to the string, etc. will cause the two strings to be unequal. Therefore, it is recommended to use the third equal sign judgment if the data type can be determined, or use strcmp or strcasecmp for strong type judgment.
The above is the detailed content of Detailed explanation of common traps in PHP numbers and strings. For more information, please follow other related articles on the PHP Chinese website!