Home >Backend Development >PHP Tutorial >An in-depth explanation of the careful use of double equals (==) in PHP_PHP Tutorial
PHP comparison operators appear too frequently, especially ==
if(a == b){
// do something
}
But, you really Have you mastered ==? Details matter!
Look at the code below and tell what you think is the correct answer
var_dump(' 123fg456'==123);
var_dump('some string' == 0);
var_dump(123.0 = = '123d456');
var_dump(0 == "a");
var_dump("1" == "01");
var_dump("1" == "1e0");
Come up with your answer first, then run it again and see. If the answer is correct, congratulations, your basic knowledge is very solid.
Explanation:
If you compare an integer and a string, the string will be converted to an integer. If comparing two numeric strings, compare as integers. This rule also applies to switch statements.
Specially note that when a string is converted to an integer, it is converted from left to right until a non-numeric character is encountered. In other words, '123abc456' will be converted to 123, not 123456. In addition, spaces at the beginning of the string will be ignored, for example, ' 234abc' is converted to 234.
A comparison table of loose comparison and strict comparison is attached below