Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Very strange behaviour in PHP [duplicate]

Tags:

php

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.

like image 332
Weltkind Avatar asked Mar 07 '16 06:03

Weltkind


2 Answers

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

like image 108
Sougata Bose Avatar answered Oct 03 '22 04:10

Sougata Bose


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
like image 40
devpro Avatar answered Oct 03 '22 06:10

devpro