This article will introduce some questions about comparing php Strings and numbers. Because numbers and characters are different data types in php, there may be many problems during comparison. This article will introduce some questions about comparing php Strings and numbers. Because numbers and characters are different data types in php, there may be many problems during comparison.
Script ec (2); script
Today, I encountered a problem. According to the interface description, the numbers 0, 1, 2, and so on are returned. 0 indicates that the operation is successful, and other values indicate different error codes. The program uses if ($ ret = 0) to determine whether the program is good. Today, a problem occurs. because the other party's interface is modified, a letter string is directly returned as an error message, then, my side is tragic. The above judgment will always be TRUE.
The reason is that php is a weak type language, so we can compare two different types of variables, but before the comparison, php will convert one party to the other, this is important. If it is a string and a number for comparison, php will forcibly convert the string to a number. For a string of pure letters, It is 0 after conversion, so if ($ ret = 0) yes.
PHP manual/Language Reference/operator/comparison operator can be found.
In PHP, when two numeric strings (strings containing only numbers) are compared, they are directly converted to numerical values for comparison.
Example: (note that the last two variables $ a and $ B are not equal)
| The Code is as follows: |
|
// Example 1 $ A = '000000 '; $ B = '000000 '; If ($ a = $ B ){ Echo 'equal '; } Else { Echo 'notequal '; } ?> |
Running the above program finds that the result is equal (not the result we think)
Add a letter a to $ a and $ B respectively.
| The Code is as follows: |
|
// Example 2 $ A = 'a0000203199106034578 '; $ B = 'a0000203199106034579 '; If ($ a = $ B ){ Echo 'equal '; } Else { Echo 'notequal '; } ?>
|
The output is notEqual (correct result)
Example 1 is equal because PHP converts two numeric strings to a numeric string, and the two numbers are exactly the same.
| The Code is as follows: |
|
$ 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 get in Example 1 is equal.
To avoid this unexpected result, use the type comparison operator ===( if $ a is equal to $ B and their types are the same)
| The Code is as follows: |
|
// Example 4 $ A = '000000 '; $ B = '000000 '; If ($ a ===$ B ){ Echo 'equal '; } Else { Echo 'notequal '; } ?> |
In this way, we can get the expected notEqual.