The result of a PHP True False statement might be different from what looks like a simple and logical result.
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) ""); // bool(false)
var_dump((bool) "0"); // bool(false)
var_dump((bool) "1"); // bool(true)
var_dump((bool) "alpha"); // bool(true)
PHP INT, FLOAT
var_dump((bool) 1); // bool(true)
var_dump((bool) -1); // bool(true)
var_dump((bool) 2.3e5); // bool(true)
var_dump((bool) -2); // bool(true)
var_dump((bool) 0.0); // bool(false)
var_dump((bool) -0.1); // bool(true)
PHP ARRAYS
var_dump((bool) array()); // bool(false)
var_dump((bool) array(5)); // bool(true)
OTHERS
var_dump((bool) "false"); // bool(true)
var_dump((bool) NULL); // bool(false)
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);
//result: int(0)
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'";}
//result: 'a' not found in 'abc xyz'
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.
Top comments (2)
My favorite :
:) from now on, I will always check constants before refactoring a code.