PHP NULL

NULL is a special type that represents a variable with no value.

NULL is a special data type that has only one value: NULL. A variable is NULL if it has been assigned the constant NULL, has not been set, or has been unset with unset().

Use is_null() or isset() to check for it.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Initialise an optional config value to null before conditionally assigning it from user input.
  • Check is_null() on a database query result to determine whether a record was found.
  • Set a session variable to null to clear it without calling unset() when resetting state.

More examples

Assigning and checking null

Initialising to null and checking is_null() clearly expresses intent before lazy assignment.

Example Β· php
<?php
$token = null;

if (is_null($token)) {
    $token = bin2hex(random_bytes(16));
}
echo $token;

null with isset and empty

isset() returns false for null variables, making it the right guard for nullable values.

Example Β· php
<?php
$user = null;

var_dump(isset($user));   // bool(false)
var_dump(empty($user));   // bool(true)
var_dump(is_null($user)); // bool(true)

Nullable type declarations

The ?array return type signals null is a valid return value, which ?? then handles cleanly.

Example Β· php
<?php
function findUser(int $id): ?array {
    $users = [1 => ["name" => "Alice"]];
    return $users[$id] ?? null;
}

$user = findUser(99);
echo $user === null ? "Not found" : $user["name"];

Discussion

  • Be the first to comment on this lesson.
PHP NULL β€” PHP | SoundsCode