Very strange behavior in PHP

I have this code:

$test = 0; if ($test == "on"){ echo "TRUE"; } 

The result of this code will be:

 TRUE 

WHY??? My PHP version is: 5.4.10.

+5
source share
5 answers

If you are comparing a number with a string or the comparison includes numeric strings, each string is converted to a number and the comparison is performed numerically. These rules also apply to the switch statement. Type conversion does not occur when comparison === or! ==, as this includes a comparison of type and value.

 $test = 0; if ($test === "on"){ echo "TRUE"; } 

PHP converts the string to a number for comparison. Using === , compare the value as well as the data type.

 var_dump(0 == "a"); // 0 == 0 -> true var_dump("1" == "01"); // 1 == 1 -> true var_dump("10" == "1e1"); // 10 == 10 -> true var_dump(100 == "1e2"); // 100 == 100 -> true 

Documentation

+3
source

Since you are comparing $test with a string value, not a binary value, if you want to compare with a string value, try comparing === , for value + dataType .

In your example, var_dump(0=="on"); always returns bool(true) .

But when you use var_dump(0==="on"); , it will give you bool(false) .

An example from the PHP manual :

 var_dump(0 == "a"); // 0 == 0 -> true var_dump("1" == "01"); // 1 == 1 -> true var_dump("10" == "1e1"); // 10 == 10 -> true var_dump(100 == "1e2"); // 100 == 100 -> true 
+4
source

If you are comparing a number with a string or the comparison includes numeric strings, each string is converted to a number and the comparison is performed numerically. These rules also apply to the switch statement. Type conversion does not occur when comparison === or! ==, as this includes a comparison of type and value.

Therefore, use the comparison "===" for comparison.

Refer to the link: http://php.net/manual/en/language.operators.comparison.php

+3
source

This is because you do ==
0 is an integer, so in this, on converted to int, which is 0, so your if statement looks like 0==0

To solve, you should use ===

 if ($test === "on") 
0
source

In PHP, a free comparison of an integer and a non-numeric string (i.e. a string that cannot be interpreted as a numeric one, for example, "php" or in your case "on") will cause the string to be interpreted as an integer with a value 0 Please note that the numeric "43", "1e3" or "123" is a numeric string and will be correctly interpreted as a numeric value.

I know this is weird.

0
source

Source: https://habr.com/ru/post/1244554/


All Articles