Home > Article > Backend Development > String and integer comparison in php
Today when dealing with loops in php, there was a comparison operation, but the result was never predicted by myself, so I tracked it and found that when comparing strings with integers, the strings will be converted into The integers are then compared. This will not be a problem in strongly typed languages such as Java and C, because they will convert the strings and then compare them. However, in weakly typed languages such as PHP, there will be problems when direct comparisons can be made.
$a = "梦回故里"; if($a==0){ echo "等于"; }else{ echo "不等于"; }
For example, in the following code, I initially thought it would output not equal, because $a should be true according to our understanding, and it should be 1, so it is not equal anyway. But the result is equal to. Because $a will be converted to an integer, the conversion will start from the first character. If it is not an integer, it will be converted to 0.
For example, the following example:
$a = "梦回故里1"; if(0==$a){ echo "等于"; }else{ echo "不等于"; }
This will still output equal to, because the A dream word is not an integer, so it is converted to 0.
$a = "1梦回故里"; if(0==$a){ echo "等于"; }else{ echo "不等于"; }
This will output not equal, because the first one is 1, it will be converted to 1, and then compared, so it is not equal.
The PHP language is like this. It provides us with enough freedom and is easy to learn, but we must lay a solid foundation and pay attention to details. details make a difference.
For more PHP related knowledge, please visit PHP Chinese website!
The above is the detailed content of String and integer comparison in php. For more information, please follow other related articles on the PHP Chinese website!