PHP null

Created with Sketch.

PHP null

Summary: in this tutorial, you will learn about the PHP NULL type and how to check if a variable is null or not.

Introduction to the PHP null type

The null is a special type in PHP. The null type has only one value which is also null. In fact, null indicates the absence of a value for a variable.

A variable is null when you assign null to it like this:

<?php

$email = null;
var_dump($email); // NULL

Code language: HTML, XML (xml)

In addition, when you use the unset() function to unset a variable, the variable is also null. For example:

<?php

$email = 'webmaster@phptutorial.net';
unset($email);

var_dump($email); // NULL

Code language: HTML, XML (xml)

PHP NULL and case-sensitivity

PHP keywords are case-insensitive. Therefore, NULL is also case-insensitive. It means that you can use null, Null, or NULL to represent the null value. For example:

<?php

$email = null;
$first_name = Null;
$last_name = NULL;

Code language: HTML, XML (xml)

It’s a good practice to keep your code consistent. If you use null in the lowercase in one place, you should also use it in your whole codebase.

Testing for NULL

To check if a variable is null or not, you use the is_null() function. The is_null() function returns true if a variable is null; otherwise, it returns false. For example:

<?php

$email = null;
var_dump(is_null($email)); // bool(true)

$home = 'phptutorial.net';
var_dump(is_null($home)); // bool(false)

Code language: HTML, XML (xml)

To test if a variable is null or not, you can also use the identical operator ===. For example:

<?php

$email = null;
$result = ($email === null);
var_dump($result); // bool(true)

$home= 'phptutorial.net';
$result = ($home === null);
var_dump($result); // bool(false)

Code language: HTML, XML (xml)

Summary

  • PHP null type has a value called null that represents a variable with no value.
  • Use the is_null() function or === operator to compare a variable with null.

Leave a Reply

Your email address will not be published. Required fields are marked *