null means no value. It is the only value of the null type, and it is written null (case does not matter, but lowercase is the standard).
<?php
$middleName = null;
var_dump($middleName);
NULL
When a variable is null
A variable is null when:
- You assign
nullto it. - You never gave it a value (PHP also gives a warning when you read it).
- You called
unset()on it.
A function that has nothing to return also gives null.
<?php
function sayHi(): void
{
echo "Hi\n";
}
$result = sayHi();
var_dump($result);
Hi
NULL
Checking for null
<?php
$value = null;
var_dump($value === null);
var_dump(is_null($value));
var_dump(isset($value));
bool(true)
bool(true)
bool(false)
null is not 0 and not “”
These three look similar but mean different things.
| Value | Meaning |
|---|---|
null | No value at all |
0 | The number zero |
"" | A string with no characters |
<?php
var_dump(null === 0);
var_dump(null === "");
var_dump(null == false);
bool(false)
bool(false)
bool(true)
Loose comparison (==) treats null as equal to false, 0 and "". Strict comparison (===) does not. That is why professional PHP uses ===.
A default for null
The null coalescing operator ?? gives a fallback when a value is null or missing.
<?php
$nickname = null;
echo $nickname ?? "No nickname";
No nickname
More on that in Null Coalescing Operator.
null is how you say "optional"
null.