PHP empty

Created with Sketch.

PHP empty

Summary: in this tutorial, you’ll learn how to use the PHP empty() construct to check if a variable is empty.

Introduction to the PHP empty() construct

The empty() construct accepts a variable and returns true if the variable is empty. Otherwise, it returns false.

empty(mixed $v): bool

Code language: PHP (php)

A variable is empty when if it does not exist or if its value is equal to false. In other words, a variable that is not set is empty or its value equals the following:

The false
The integer 0
The float 0.0 and -0.0
The string "0"
The empty string ''
An array with no element
null
SimpleXML objects created from empty elements that have no attributes.

Code language: PHP (php)

The empty($v) is essentially the same as the following expression that uses the isset() and equality (==) operator:

!isset($v) || $v == false

Code language: PHP (php)

Like the isset() construct, the empty() is a language construct, not a function. Therefore, you cannot call it using variable functions.

However, you can work around it by defining a function that uses the empty() construct and call that function using variable functions:

<?php

function not_exist_or_false($var) : bool
{
return empty($var);
}

Code language: HTML, XML (xml)

Alternatively, you can use the arrow function syntax to define a new function that uses the empty() construct:

<?php

$empty = fn($var) => empty($var);

Code language: HTML, XML (xml)

PHP empty() examples

The following example returns true because the $count variable is not declared:

<?php

var_dump(empty($count));

Code language: PHP (php)

Output:

bool(true)

Code language: PHP (php)

The following example also returns true because $count is zero, which is considered false:

<?php

$count = 0;
var_dump(empty($count));

Code language: PHP (php)

Output:

bool(true)

Code language: PHP (php)

If a variable’s value is false, then the empty() returns true. The following returns true for all the falsy values in the $falsy_values array:

<?php

$falsy_values = [false, 0, 0.0, "0", '', null, []];

foreach($falsy_values as $value) {
var_dump(empty($value));
}

Code language: PHP (php)

When to use the PHP empty() construct

In practice, you use the empty() construct in the situation that you’re not sure if a variable even exists.

For example, suppose you receive an array $data from an external source, e.g., an API call or a database query.

To check if the $data array has an element with the key 'username' and it is not empty, and you may use the following expression:

isset($data['username']) && $data['username'] !== '')

Code language: PHP (php)

However, it’s shorter you use the empty() construct:

!empty($data['username'])

Code language: PHP (php)

Summary

  • Use the PHP empty() construct to check if a variable is not set or its value is false.

Leave a Reply

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