String and integer comparison in php

angryTom
Release: 2023-04-07 16:16:02
forward
2591 people have browsed it

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 "不等于";
}
Copy after login

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 "不等于";
}
Copy after login

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 "不等于";
}
Copy after login

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!

Related labels:
source:zyan.cc
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