Home  >  Article  >  Backend Development  >  Detailed explanation of common traps in PHP numbers and strings

Detailed explanation of common traps in PHP numbers and strings

伊谢尔伦
伊谢尔伦Original
2017-06-21 13:11:071631browse

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:

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

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

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)

Explain with an example

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!

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