Categories: Development

PHP isset() vs empty() vs is_null() comparison

A PHP isset, empty, and is null helper function comparison with a table for variables and common types.

Quick rundown

isset() returns true when the variable has a value, is not null or a declared and not assigned variable.

empty() empty returns true for an empty string, null, 0 as string and int or false.

is_null() will return true only for a null value or when the variable is declared but not assigned.

Summary

Isset is the opposite of is_null, it can be applied to unknown variables to check if they “are set”. is_null can only be used on variables that exist and serves as a method for variables that exist but are not assigned or are null. Empty can be seen as a type of middle ground.

Comparison table

Using PHP version 8.0.0

$var value isset($var) empty($var) is_null($var)
” (empty) bool(true) bool(true) bool(false)
‘ ‘ (space) bool(true) bool(false) bool(false)
false bool(true) bool(true) bool(false)
true bool(true) bool(false) bool(false)
array() bool(true) bool(true) bool(false)
null bool(false) bool(true) bool(true)
‘0’ bool(true) bool(true) bool(false)
0 bool(true) bool(true) bool(false)
0.0 bool(true) bool(true) bool(false)
$var; bool(false) bool(true) bool(true)
Share
Tags: PHPWeb Dev

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago