Real World PHP

About   |   EN   |   ES

006e Data Types: NULL

NULL is a special constant that only has the value null.

The value "null" conveys the idea of having no value, which is different from an empty string(""), the number zero (0), or an empty array ([]). It is very helpful.

You can assign NULL to a variable by the assignment operator:

<?php
$a = NULL;

NULL is case-insensitive. PHP will treat "NULL" the same as "nULL" or "Null" or "null." By convention, we use all uppercase.

You can also remove the value of a variable by using the unset() function. It will essentially destroy the variable and will evaluate to null after that. Note that trying to access an undefined variable will cause PHP to throw a warning as well.

<?php
$a = 5;
unset($a);
var_dump($a); // $a is now NULL (will also display a warning.)

While it was possible to cast a variable to null in previous version of PHP, it is no longer supported in the most recent versions.


Resources


Challenges

Experiments with NULL

Discover what happens when you var_dump() a variable in the following conditions:

  • before it has been defined
  • when it has been defined and set to the value NULL
  • when it has been defined and set to the value 300, then unset()

Note the difference in the output. Why are the outputs different?