0 A string comparison (= = =) that is preceded by any non-numeric (or character that cannot be converted to a number) returns True.
The reason is that when a number is compared to a string, the first attempt is to convert the string to a number, and then compare it to a string that cannot be converted to a number, and the result is 0, so it always returns true compared with 0.
More detailed comparison rules, multiple types of comparison rules, can be found in the PHP manual/Language Reference/Operator/comparison operator .
In PHP, when you compare two numeric strings (strings that contain only numbers), you convert them directly to numeric values for comparison.
The following example: (Note that the last one of the two variables $a and $b is not equal)
Copy Code code as follows:
Example 1
<?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 think)
We're going to add $a and $b a letter A.
Copy Code code as follows:
Example 2
<?php
$a = ' a511203199106034578 ';
$b = ' a511203199106034579 ';
if ($a = = $b) {
echo ' equal ';
} else {
Echo ' notequal ';
}
?>
This time the output is notequal (the correct result)
Example 1 is equal because PHP converts two numeric strings to numbers, and these two numbers just equal the following example
Copy Code code as follows:
<?php
$a = 511203199106034578;
$b = 511203199106034579;
echo $a; Output 5.1120319910603E+17 that is 511203199106030000
Echo $b; Output 5.1120319910603E+17 that is 511203199106030000
?>
So the result we got in Example 1 is equal.
To avoid this unintended result, use the type comparison character = = = Example (if $a equals $b and their type is the same)
Copy Code code as follows:
Example 4
<?php
$a = ' 511203199106034578 ';
$b = ' 511203199106034579 ';
if ($a = = = $b) {
echo ' equal ';
} else {
Echo ' notequal ';
}
?>
So we can get the expected notequal.