Operation Method of String and Integer Comparison in php

  • 2021-12-12 03:57:38
  • OfStack

Today, when dealing with the loop in php, there is a comparison operation, but the result 1 is not predicted by itself, so I tracked it under 1, and found that when comparing strings with integers, I will convert strings into integers and then compare them. This won't be a problem in strong-typed languages like java and c, because they convert strings and compare them, but in weak-typed languages like php, when you can compare them directly, you will have a problem.


$a = " Dream back to one's hometown ";
if($a==0){
    echo " Equal to ";
}else{
  echo " Not equal to ";
}

For example, in the following code, 1 starts to think that the output is not equal, because $a should be an true according to our understanding, and he should be 1, so it is not equal. But the result is equal to. Because $a is converted to an integer, the conversion starts with the first character and is converted to 0 if it is not an integer.

For example, the following example:


$a = " Dream back to one's hometown 1";
if(0==$a){
    echo " Equal to ";
}else{
  echo " Not equal to ";
}

This will still output equal, because the first dream word is not an integer, so it is converted to 0.


$a = "1 Dream back to one's hometown ";
if(0==$a){
    echo " Equal to ";
}else{
  echo " Not equal to ";
}

This will output not equal, because the first one is 1, and it will be converted to 1, and then compared, so it is not equal.

This is the case with php language, which provides us with enough freedom and is simple to learn, but we must lay a solid foundation and pay attention to details. Details determine success or failure.

Summarize


Related articles: