PHP Reference ยท Types and Type Handling
The PHP null value
Reference for PHP null: when a variable is null, how isset(), is_null() and ?? treat it, null in comparisons and arrays, and nullable types.
null is the type with exactly one value, also called null. It means "no value": a variable that has not been given a value, a function that found nothing, or a property that is deliberately empty. The keyword is case-insensitive (NULL and Null work), but the modern style is lowercase.
A variable is null when you assign null to it, when it was never assigned (reading it also emits a warning), or after you call unset() on it. A function without a return value returns null too.
$value = null; var_dump(is_null($value)); // bool(true) var_dump($value ?? "fallback");
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
$x = null; if ($x === null) { /* ... */ } $value = $x ?? $default; $x ??= "set once"; function f(?int $n = null): ?string { return null; }
| Check | null result |
|---|---|
is_null($x), $x === null |
true |
isset($x) |
false |
empty($x) |
true |
$x ?? $y |
$y |
(bool) null |
false |
(int) null, (float) null |
0, 0.0 |
(string) null |
"" |
(array) null |
[] |
Usage notes
- Prefer
=== nulloris_null()for "has no value".==treatsnullas equal tofalse,0,""and[], which hides bugs. (null == "0"is false, becausenullis compared as an empty string.) isset()and??quietly treat null as unset, and never warn about missing variables or array keys. Usearray_key_exists()to tell a missing key from a key whose value isnull.- Nullable types.
?stringis shorthand forstring|null. A parameter typed?stringstill must be passed; add= nullto make it optional. - Null is not a valid argument to many built-ins. Since PHP 8.1, passing
nullto a non-nullable internal parameter such asstrlen(null)is deprecated, and a future version will throw aTypeError. - Arithmetic on null treats it as
0, and concatenation treats it as"", with no warning. - Returning null on failure is a common API style; make the intent clear with a
?Typereturn type and document it, or throw an exception when failure is exceptional. nullas a standalone type (for examplefunction f(): null) is allowed since PHP 8.2; before that it could only appear in a union such as?intorint|null.- The nullsafe operator
?->short-circuits a whole chain tonullwhen the left side isnull. See Nullsafe operator. - Uninitialized typed properties are not
null: reading one before assignment throws anError.