tellmewhen string PHP is easy to ignore and make errors. Comparison of numbers and strings

WBOY
Release: 2016-07-29 08:47:09
Original
1448 people have browsed it

0 will return true when compared with any leading string that is not a number (or, in other words, a character that cannot be converted to a number) (the operator is ==).

The reason is that when comparing numbers with strings, try to first Convert the string to a number and then compare it. If a string cannot be converted to a number, the conversion result is 0. Therefore, comparing with 0 always returns true.

More detailed comparison rules, multiple types of comparison rules, in PHP You can find it in Manual/Language Reference/Operators/Comparison Operators.
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 that the last digits of the two variables $a and $b are not equal)

Copy the 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 think)
We add a letter a to $a and $b respectively

Copy the code The code is as follows:


//Example 2
$a = 'a511203199106034578 ';
$b = 'a511203199106034579';
if ($a==$b) {
echo 'equal';
} else {
echo 'notEqual';
}
?>


Output this time It is notEqual (correct result)
Example 1 is equal because PHP converts two numeric strings into numeric types, and the two numbers are exactly equal. 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 the 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

The above introduces the tellmewhen string PHP pitfalls that can easily be ignored and lead to errors. The comparison of numbers and strings includes the tellmewhen string aspect. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template