Home >Backend Development >PHP Tutorial >PHP is easy to ignore and lead to error traps. Comparing numbers and strings_PHP Tutorial

PHP is easy to ignore and lead to error traps. Comparing numbers and strings_PHP Tutorial

WBOY
WBOYOriginal
2016-07-21 15:23:01711browse

0 Compares (operator ==) with any leading string that is not a number (or, in other words, a character that cannot be converted to a number), and 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.

More detailed comparison rules, multiple types of comparison rules, can be found in PHP Manual/Language Reference/Operators/Comparison Operators.

Be used as two in PHP When comparing numeric strings (strings containing only numbers), they are directly converted into numerical values ​​for comparison
The following example: (note that the last digits of the two variables $a and $b are not equal)

Copy code The code is as follows:

//Example 1
$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 add a letter a to $a and $b respectively

Copy code The code is as follows:

//Example 2
$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 combines two numeric strings Convert to numeric type, and the two numbers are exactly equal to the following example
Copy the code The code is as follows:

$a = 511203199106034578;
$b = 511203199106034579;
echo $a; // Output 5.1120319910603E+17 which is 511203199106030000
echo $b; // Output 5.1120319910603E+17 which is 511203199106030000
?>

So the result we got in example 1 is equal

To avoid this unexpected result is to use the type comparison operator === as in the following example ( If $a is equal to $b, and their types are also the same)
Copy code The code is as follows:

//Example 4
$a = '511203199106034578';
$b = '511203199106034579';
if ($a===$b) {
echo 'equal';
} else {
echo 'notEqual';
}
?>

This way we can get the expected notEqual

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/324586.htmlTechArticle0 String comparison (operator) with any leading non-number (or, in other words, character that cannot be converted to a number) is ==), all return true. The reason is that when comparing numbers and strings, first try to convert the string...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn