The Analogy: The Stores Counter And Its Bin Cards
Behind the stores counter of any factory is a rack of pigeonholes, one per part number, and in each pigeonhole sits a bin card: a little printed slip recording how many of that part are on the shelf. When a fitter comes to the hatch and asks for six of part number 4471, the storeman does not go and count the shelf. He pulls the bin card and reads it. The whole system runs on the card standing in for the thing, and on the storeman asking the right question of the card.
The trouble is that there are three different questions he can ask, and a careless storeman runs them together. The first is "is there a bin card for this part at all?" -- has this part number ever been set up in the system, or is the pigeonhole simply not there. The second is "does the card amount to nothing worth acting on?" -- is it missing, or blank, or does it read zero. The third is "what exactly does the card say?" -- the actual number written on it. These are the three questions PHP answers with isset(), empty(), and a plain read of the value, and confusing them is the single richest source of bugs in day-to-day PHP.
The card that reads exactly "0" is where the careless storeman comes unstuck. A bin card reading zero is not the same as an empty pigeonhole. Zero is a fact: we stock this part, we have run out, and someone must reorder it. An empty pigeonhole is the absence of a fact: we do not stock this part, so there is nothing to reorder and no shortage to worry about. A storeman who treats "the card says zero" and "there is no card" as the same thing will either reorder parts the firm deliberately discontinued, or -- far worse -- fail to reorder a part that is genuinely out of stock, because he waved both away as "nothing there". That exact conflation is what PHP's empty() invites, because empty() reports true for a real zero just as it does for a missing key.
The failure mode, then, is not a crash. It is a decision made on the wrong question. The code asks empty($quantity) -- "is this nothing worth acting on?" -- when it meant to ask isset($quantity) -- "do we have a figure at all?" -- or when it meant to compare the figure against a reorder level. The program runs cleanly, the report prints, and a discontinued part quietly appears on the purchase order while a stocked-out part quietly does not. This lesson is about knowing which of the three questions you are actually asking, and reaching for the operator that asks exactly that one.
Syntax or Core Structure
In a boolean context -- an if, a while, the operand of && -- PHP converts whatever it is given to true or false. A fixed, short list of values convert to false; everything else converts to true. Knowing that list by heart is the foundation of everything else in this lesson.
<?php
declare(strict_types=1);
$values = [
['false', false],
['0', 0],
['0.0', 0.0],
['"0"', "0"],
['""', ""],
['[]', []],
['null', null],
['"0.0"', "0.0"],
['"00"', "00"],
['" "', " "],
['"false"', "false"],
['-1', -1],
['[0]', [0]],
];
foreach ($values as [$label, $v]) {
printf("%-8s %s%s", $label, $v ? 'true' : 'false', PHP_EOL);
}
Output:
false false
0 false
0.0 false
"0" false
"" false
[] false
null false
"0.0" true
"00" true
" " true
"false" true
-1 true
[0] true
The falsy half of that list is the whole list -- there are exactly these falsy values in PHP and no others: false, the integer 0, the float 0.0, the string "0", the empty string "", the empty array [], and null (plus an unset variable, which behaves as null). The truthy half is where the surprises live. The string "0.0" is truthy even though the float 0.0 is falsy, because only the exact one-character string "0" is special; "00" and " " and "false" are all non-empty strings and therefore true. And -1 is truthy: PHP's rule is "zero is false", not "negative is false". The array [0] is truthy because it has an element -- only the empty array is falsy, regardless of what a non-empty one contains.
Technical Depth: The Three Questions
Truthiness is the coarsest of the tools. Most real code does not want "is this truthy?"; it wants one of three sharper questions, and PHP has a distinct construct for each. Getting them straight is what separates code that handles a real zero correctly from code that does not.
isset, empty And array_key_exists
isset($x) asks "does this exist and is it not null?" -- it is false for a missing key and for a key whose value is null, which means it cannot tell those two apart. empty($x) asks "is this missing or falsy?" -- it is true for a missing key, null, 0, "0", "", [] and false alike. array_key_exists($k, $a) asks the narrowest question of all: "is this key present?", and it answers true even when the stored value is null. The null coalescing $x ?? 'default' reads the value but substitutes the default only when it is null or missing, leaving every other falsy value untouched.
| Construct | True when | Blind to |
|---|---|---|
isset($x) | present and not null | cannot distinguish null from missing |
empty($x) | missing, null, or any falsy value | cannot distinguish 0 from absent |
array_key_exists($k, $a) | key present, even if null | ignores the value entirely |
$x ?? $d | yields $x unless null/missing | leaves 0, "", "0", [] as they are |
<?php
declare(strict_types=1);
$bin = ['A' => 42, 'B' => 0, 'C' => null, 'D' => '', 'E' => '0'];
$fmt = "%-3s %-6s %-6s %-6s %8s";
printf("{$fmt}%s", 'KEY', 'exists', 'isset', 'empty', 'coalesce', PHP_EOL);
foreach (['A', 'B', 'C', 'D', 'E', 'F'] as $k) { // F is a missing key
$exists = array_key_exists($k, $bin) ? 'yes' : 'no';
$set = isset($bin[$k]) ? 'yes' : 'no';
$mt = empty($bin[$k]) ? 'yes' : 'no';
$co = $bin[$k] ?? 'def';
$coText = $co === '' ? '""' : (string) $co;
printf("{$fmt}%s", $k, $exists, $set, $mt, $coText, PHP_EOL);
}
Output:
KEY exists isset empty coalesce
A yes yes no 42
B yes yes yes 0
C yes no yes def
D yes yes yes ""
E yes yes yes 0
F no no yes def
Read the B and C rows against each other and the whole point lands. B holds a genuine zero and C holds null, yet empty says "yes" to both -- it cannot tell the out-of-stock part from the discontinued one. isset does tell them apart: it is "yes" for B and "no" for C, because isset treats null as good as absent. Only array_key_exists reports the literal truth that both keys are present. And the coalesce column shows the quietest trap of all: ?? replaces C (null) and F (missing) with def, but it leaves B's 0, D's "" and E's "0" exactly as they were, because those are not null. If you reach for ?? expecting it to supply a default for an empty string, it will not.
The "0" String In Form Input
The string "0" being falsy is not an academic curiosity; it is a live bug in form handling. A user who types 0 into a quantity field, or a house number of 0, or the answer 0 to "how many dependents?", sends the string "0", and if (empty($_POST['qty'])) will treat that legitimate answer as if the field were blank. Validate presence with isset or array_key_exists, validate blankness with === '' or trim($x) === '', and validate the number by casting and range-checking it -- never fold all three into a single empty().
Real World Example: The Stores Reorder Report
The stores system runs a nightly report: for every part it holds a card, it decides whether to reorder. A part with a null on-hand figure has been discontinued and must be left alone; a part whose on-hand is below its reorder level -- including a genuine zero -- must be reordered up to twice the level. The whole report hinges on telling "discontinued" (null) apart from "out of stock" (zero), which is precisely the distinction empty() would destroy.
<?php
declare(strict_types=1);
// on-hand of null means the line was discontinued; 0 means genuinely empty.
$parts = [
['P1', 'bolt', 0, 20],
['P2', 'washer', 150, 50],
['P3', 'gasket', null, 30],
['P4', 'nut', 8, 20],
['P5', 'clip', 40, 40],
['P6', 'seal', 5, 25],
['P7', 'pin', null, 15],
];
$fmt = "%-4s %-7s %4s %4s %-8s %6s";
$rule = str_repeat('-', 38);
printf("{$fmt}%s", 'PART', 'NAME', 'OH', 'LVL', 'STATE', 'ORDER', PHP_EOL);
echo $rule, PHP_EOL;
$reorder = 0;
$disc = 0;
$ok = 0;
$orderTotal = 0;
foreach ($parts as [$id, $name, $onHand, $level]) {
if ($onHand === null) { // strict: only true null, never 0
$disc++;
$ohText = '--';
$state = 'SKIP';
$orderText = '-';
} elseif ($onHand < $level) { // a real 0 lands here, correctly
$order = $level * 2 - $onHand;
$orderTotal += $order;
$reorder++;
$ohText = (string) $onHand;
$state = 'REORDER';
$orderText = (string) $order;
} else {
$ok++;
$ohText = (string) $onHand;
$state = 'ok';
$orderText = '-';
}
printf("{$fmt}%s", $id, $name, $ohText, $level, $state, $orderText, PHP_EOL);
}
echo $rule, PHP_EOL;
printf("reorder %d discontinued %d ok %d of %d parts order total %d%s",
$reorder, $disc, $ok, count($parts), $orderTotal, PHP_EOL);
Output:
PART NAME OH LVL STATE ORDER
--------------------------------------
P1 bolt 0 20 REORDER 40
P2 washer 150 50 ok -
P3 gasket -- 30 SKIP -
P4 nut 8 20 REORDER 32
P5 clip 40 40 ok -
P6 seal 5 25 REORDER 45
P7 pin -- 15 SKIP -
--------------------------------------
reorder 3 discontinued 2 ok 2 of 7 parts order total 117
The report gets the two zero-ish cases exactly right, and it does so because it asks the right question in the right order. P1 is a bolt with zero on hand: the === null test is false (it is 0, not null), so it falls to the < $level test, is below 20, and is reordered up to 40. P3 is a discontinued gasket with null on hand: the === null test catches it first, marks it SKIP, and it never reaches the numeric comparison. The order total of 117 is the sum of the three REORDER lines, 40 plus 32 plus 45, and the three category counts add to the seven parts.
Now consider the design flaw, which is a real one and not a rough edge: the guard $onHand < $level will misbehave the day the data is not as clean as this batch. If a part's on-hand figure arrives as the string "" -- which is exactly what an empty cell in an imported CSV becomes -- then "" === null is false, so it is not treated as discontinued, and "" < 20 coerces the empty string in a comparison and, under PHP 8's rules, evaluates as 0 < 20, which is true, so an empty-celled part is silently reordered as if it were out of stock. The strict === null check protects against a real null but not against the several other ways a "missing" value sneaks in through real data. The fix is to normalise on-hand at the boundary -- reject or convert anything that is not a genuine integer or a genuine null before the loop ever sees it -- so that by the time the reorder logic runs, $onHand is provably one of exactly two shapes and the === null test carries the full weight it appears to.
Common Mistakes
- Using
empty()to test a numeric field.empty($qty)is true for a
real 0, so a legitimate quantity of zero is treated as "not supplied". When zero is a valid value -- a count, a balance, a house number -- test presence with isset and validity with a numeric comparison, never with empty.
- Assuming
issetdistinguishes null from missing.isset($a['k'])is
false both when the key is absent and when it is present but null. If that difference matters -- as it does when null means a deliberate "no value" -- reach for array_key_exists, which reports the key's presence regardless of its value.
- Expecting
??to replace empty strings.$name ?? 'Anon'leaves an
empty string "" in place, because ?? only substitutes for null or missing. If a blank string should also fall back, you need $name !== '' ? $name : 'Anon' or a trim-and-check, not ??.
- Treating the string
"0"as truthy. It is the one non-empty string
that is falsy, so if ($input) silently rejects a user who typed 0. Whenever a field can legitimately be "0", test it explicitly rather than leaning on its truthiness.
- Confusing
== nullwith=== null.$x == nullis true for every
falsy value -- 0, "", [], false -- because of loose coercion, so it is a terrible "is this null?" test. Use $x === null or is_null($x), both of which are true for null and nothing else.
- Calling
is_nullor reading a value on a key that may be missing.
is_null($a['k']) and $a['k'] === null both emit an "Undefined key" warning when the key is absent, even though they then evaluate as you might hope. Guard with array_key_exists first, or use ($a['k'] ?? null) === null, which is warning-free.
- Relying on
0.0and"0.0"behaving alike. The float0.0is
falsy but the string "0.0" is truthy, because only the exact string "0" is the special case. Numbers arriving as strings from a database or form do not follow the same truthiness as their numeric forms; cast before you test.
- Using truthiness to check an array has contents you can use. `if
($rows) is true for any non-empty array, but says nothing about whether the element you are about to read exists. A non-empty array can still lack the key you want, so follow the truthiness check with an explicit isset or array_key_exists` on the specific element.
- Folding presence, blankness and validity into one test. `if
(empty($_POST['email'])) tries to answer "was it sent, is it blank, is it valid" in one word and answers all three badly. Separate the questions: isset for sent, === ''` for blank, a validator for valid.
Best Practices
- Learn the falsy list by heart --
false,0,0.0,"0","",
[], null -- because every truthiness decision you make is really a question about whether your value is one of those seven. Everything else is truthy.
- Match the construct to the question.
issetfor "present and not null",
array_key_exists for "present at all", empty only for "missing or falsy and I genuinely mean all of those", and an explicit comparison for anything about the actual value.
- Reserve
empty()for the case where every falsy value truly should be
treated the same, and add a comment saying so. In most business logic that is not what you want, and reaching for empty out of habit is how zero-valued data gets lost.
- Use
=== nulland!== nullfor null checks, never== null. Strict
comparison to null is true for null alone; loose comparison drags in every other falsy value and turns a null check into a truthiness check by accident.
- Normalise external input at the boundary. Convert form and CSV fields to
their real types -- int, string, or a deliberate null -- as they enter, so the rest of the program can trust that a value is one of a known set of shapes and truthiness tests behave predictably.
- Prefer
($array[$key] ?? null)to read a possibly-absent key without a
warning, then test the result explicitly. It is warning-free, it reads clearly, and it keeps you from sprinkling @ error suppression through the code.
- When zero, empty string, or the string
"0"are legitimate values in your
domain, write a test that names them. $qty !== null && $qty !== '' states the intent far better than !empty($qty), and it will not silently drop the valid zero.
- Keep the three questions visibly separate in validation code. One line to
check the field was submitted, one to check it is not blank, one to check it is valid -- so that a failure points at exactly which condition was not met rather than at a single overloaded empty.
Practice Exercises
- Print the falsy list. Write a script that loops over
false,0,
0.0, "0", "", [], null, and also "0.0", "00", " " and [0], printing each with its boolean cast. Confirm which four of the last group are truthy and write one sentence explaining why "0.0" differs from 0.0.
- The predicate table. Build an array with one key holding
42, one
holding 0, one holding null, one holding "", and leave one key absent. For each key print whether array_key_exists, isset, and empty are true, and what $a[$k] ?? 'def' yields. Point at the row that proves isset cannot tell null from missing.
- Fix the form handler. Take a snippet that reads a quantity with `if
(empty($_POST['qty'])) { $qty = 1; } and rewrite it so that a submitted 0` is kept as zero, a missing field defaults to 1, and a blank field is rejected as an error. Show the three cases producing three different outcomes.
- Harden the reorder report. Extend the stores report to accept on-hand
values that may arrive as the string "" for a missing figure, and make an empty string mean "unknown, flag for a stock check" rather than either discontinued or out of stock. Prove that a genuine 0, a null, and an "" now each land in a different branch.