6

I have this code:

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

Result of this code will be:

TRUE

WHY??? My version of PHP: 5.4.10.

Weltkind
  • 687
  • 5
  • 9

5 Answers5

5

If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically. These rules also apply to the switch statement. The type conversion does not take place when the comparison is === or !== as this involves comparing the type as well as the value.

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

PHP will convert the string to number to compare. Using ===, will compare the value as well as the type of data.

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

Docs

Sougata Bose
  • 31,517
  • 8
  • 49
  • 87
4

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

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

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

Example from 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
devpro
  • 16,184
  • 3
  • 27
  • 38
3

If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically. These rules also apply to the switch statement. The type conversion does not take place when the comparison is === or !== as this involves comparing the type as well as the value.

So use "===" for comparision.

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

RK12
  • 472
  • 3
  • 11
0

This is because your are doing ==
0 is integer so in this on converted to int which is 0
So your if statement looks like 0==0

For solution You have to use ===

if ($test === "on")
Divyesh Savaliya
  • 2,692
  • 2
  • 18
  • 37
0

In PHP, loose comparison between integer and non-numeric string (i.e string which cannot be interpreted as numeric, such as "php" or in your case "on") will cause string to be interpreted as integer with value of 0. Note that numeric "43", "1e3" or "123" is a numeric string and will be correctly interpreted as numeric value.

I know this is weird.

Zamrony P. Juhara
  • 5,222
  • 2
  • 24
  • 40