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…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago