In an if, PHP does not insist on a real boolean. It converts the value to true or false first. Values that become false are called falsy, and the rest are truthy.
The falsy values
false0and0.0""and"0"[](empty array)null
Everything else is truthy, including "false", "0.0", " " (a space) and any non-empty array.
<?php
$values = [0, 1, "", "0", "hello", [], [0], null, "false"];
foreach ($values as $value) {
echo json_encode($value) . " is " . ($value ? "truthy" : "falsy") . "\n";
}
0 is falsy
1 is truthy
"" is falsy
"0" is falsy
"hello" is truthy
[] is falsy
[0] is truthy
null is falsy
"false" is truthy
This is convenient
You can test for “something there” directly.
<?php
$name = "Mira";
if ($name) {
echo "Hello, $name";
}
$items = [];
if (!$items) {
echo "\nYour cart is empty.";
}
Hello, Mira
Your cart is empty.
And this is a trap
Because 0 and "0" are falsy, a legitimate value can look like “nothing”.
<?php
$quantity = "0";
if ($quantity) {
echo "Has a quantity";
} else {
echo "Treated as empty";
}
Treated as empty
If 0 is a valid answer (a quantity of zero, an age of zero, a score of zero), write an explicit comparison instead.
<?php
$quantity = "0";
if ($quantity !== "") {
echo "A quantity was entered: $quantity";
}
A quantity was entered: 0
Functions that return false on failure
Many PHP functions return false when they fail, but 0 as a valid answer. Always compare with ===.
<?php
$position = strpos("PHP", "P"); // 0, a valid position
if ($position !== false) {
echo "Found at $position";
}
Found at 0
Which style should you use?
- Use the short form (
if ($items)) for “is there anything?” checks on arrays and strings, when zero is not a valid value. - Use explicit comparisons (
=== 0,!== "",=== false) whenever zero, an empty string orfalsecould be a real answer.
The string "false"
"false" is truthy. Compare against the exact text, or use filter_var($v, FILTER_VALIDATE_BOOLEAN).