May 21 2009

NULL in PHP

In many programming lanugages there is a keyword for something which is empty, not set or an invalid pointer. So, there is null in Java, nil in Ruby, None in Python and finally NULL in PHP. Although they somehow appear to describe the same thing - be aware of their differences when switching from one programming language to another.

For example, in C++ NULL is defined as the number zero :

#define NULL 0

In PHP however, NULL is a datatype. The only possible value of NULL is NULL. That means if you assign NULL to a variable you unset the variable while assigning to it the value and type NULL - and not zero. The trapfall however is, that you need to be careful if you are checking a variable for a NULL value/type.

$var = NULL;
if ( NULL == $var ) echo "Var is NULL";
// outputs Var is NULL

The if-clause is true in this case - but this check is error-prone. Look at the following check:

$var = 0;
if ( NULL == $var ) echo "Var is NULL";
// outputs Var is NULL

This if-clause is true as well, since PHP just checks if the value of NULL and $var is equal. The converted integer value of NULL is 0

echo (int)NULL;
// outputs 0

Therefore the if clause is true. To really test if the values are equal and the type is identical you need to use the “===”-comparison operator of PHP.

Alternatively, you can use the php function is_null() to determine if a variable is of type NULL.