How does true/false work in PHP?
Solution 1:
This is covered in the PHP documentation for booleans and type comparison tables.
When converting to boolean, the following values are considered FALSE:
- the boolean
FALSE
itself - the integer
0
(zero) - the float
0.0
(zero) - the empty string, and the string
'0'
- an array with zero elements
- an object with zero member variables (PHP 4 only)
- the special type
NULL
(including unset variables) - SimpleXML objects created from empty tags
Every other value is considered TRUE.
Solution 2:
Because I've visited this page several times, I've decided to post an example (loose) comparison test.
Results:
"" -> false
"0" -> false
"0.0" -> true
"1" -> true
"01" -> true
"abc" -> true
"true" -> true
"false" -> true
"null" -> true
0 -> false
0.1 -> true
1 -> true
1.1 -> true
-42 -> true
"NAN" -> true
0 -> false
NAN -> true
null -> false
true -> true
false -> false
[] -> false
[""] -> true
["0"] -> true
[0] -> true
[null] -> true
["a"] -> true
{} -> true
{} -> true
{"t":"s"} -> true
{"c":null} -> true
Test code:
class Vegetable {}
class Fruit {
public $t = "s";
}
class Water {
public $c = null;
}
$cases = [
"",
"0",
"0.0",
"1",
"01",
"abc",
"true",
"false",
"null",
0,
0.1,
1,
1.1,
-42,
"NAN",
(float) "NAN",
NAN,
null,
true,
false,
[],
[""],
["0"],
[0],
[null],
["a"],
new stdClass(),
new Vegetable(),
new Fruit(),
new Water(),
];
echo "<pre>" . PHP_EOL;
foreach ($cases as $case) {
printf("%s -> %s" . PHP_EOL, str_pad(json_encode($case), 10, " ", STR_PAD_RIGHT), json_encode( $case == true ));
}
Summary:
- When a strict (
===
) comparison is done, everything excepttrue
returnsfalse
. - an empty string (
""
) is falsy - a string that contains only
0
("0"
) is falsy -
NAN
is truthy - an empty array (
[]
) is falsy - a container (array, object, string) that contains a falsy value is truthy
- an exception to this is
0
in""
(see the third item)
- an exception to this is
Solution 3:
Zero is false, nonzero is true.
In php you can test more explicitly using the ===
operator.
if (0==false)
echo "works"; // will echo works
if (0===false)
echo "works"; // will not echo anything
Solution 4:
The best operator for strict checking is
if($foo === true){}
That way, you're really checking if its true, and not 1 or simply just set.