The result of a PHP True False statement might be different from what looks like a simple, logical outcome.
PHP Comparison Operators == VS ===
PHP with loosely == operator will not compare type, so numeric strings will be converted to numbers and compared numerically. Below are two examples: for more on PHP comparisons, check the PHP.net page.
var_dump(0 == "a"); // 0 == 0 -> true
var_dump(10 == "1e1"); // 10 == 10 -> true
PHP strict comparison === will not convert string to a numeral. It compares both: type and the value. So examples above, comparing two of the different types, will always be false.
var_dump("1" === "01"); // 0 == "a" -> false
var_dump("10" === "1e1"); // 10 == "1e1" -> false
StackOverflow user Nick has added nice detailed comparison tables of == and === operators with TRUE, FALSE, NULL, 0, 1, -1, ‘0’, ‘1’, ‘-1’.
PHP TRUE, FALSE
In PHP: an undeclared variable, empty array, “0”, 0 and empty string are false while -1 is true. Here are some more TRUE, FALSE examples.
PHP STRINGS
var_dump((bool) "");
var_dump((bool) "0");
var_dump((bool) "1");
var_dump((bool) "alpha");
PHP INT, FLOAT
var_dump((bool) 1);
var_dump((bool) -1);
var_dump((bool) 2.3e5);
var_dump((bool) -2);
var_dump((bool) 0.0);
var_dump((bool) -0.1);
PHP ARRAYS
var_dump((bool) array());
var_dump((bool) array(5));
OTHERS
var_dump((bool) "false");
var_dump((bool) NULL);
PHP Functions
Return values of some commonly used PHP core functions might break the conditional flow by returning NULL or int() integer values. For example stripos() can return 0 which will be interpreted as false in an IF conditional block.
$text = 'abc xyz';
$pos = strpos($text, 'a');
var_dump($pos);
This code will return true with the output of string position int(0). This return value zero evaluates to the false.
if (!strpos($text, 'a')) {echo "'a' not found in '$text'";}
Above code will detect “a” but if block will evaluate to false as a’s position is 0.
Instead, explicitly check if the value returned is not FLASE
if(strpos($text, 'a') === FALSE){echo "'a' not found in '$text'";}
I am also on Twitter. You can follow me there as I regularly tweet about my journey.