PHP Empty() Function | How To Check if Array is Empty PHP

Summary: In this article, we demonstrate and explore PHP empty() function and how to check if array is empty PHP with example. Let’s understand in detail this empty function with an example.

PHP Empty() Function Definition and Usage

PHP empty() function determines whether a variable is empty, this function is an inbuilt function in PHP or you can say that the empty() function checks whether a variable is empty or not. It returns false if the variable exists and is not empty, otherwise it returns true. means that a variable is considered empty if it does not exist or if its value equals FALSE.
The following values evaluate to empty:-

  • 0
  • 0.0
  • "0"
  • ""
  • array()
  • FALSE
  • NULL

Syntax:

bool empty ( $var )

To Identify whether a variable is considered to be empty. A variable is considered empty if it doesn’t exist or if its value equals false. This function doesn’t generate a warning if the variable doesn’t exist.

Parameter Value:

This function accepts a single parameter as shown in the above syntax and described below.

Parameter Value Description
$var: Required. Variable to check whether it is empty or not.
.
Important Note:
Prior to PHP 5.5, empty() only supports the variables; anything else will result in a parse error. In other words, we can say that the following will not work: empty(trim($name)). Instead, use trim($name) == false.
No warning is generated if the variable doesn’t exist. which means empty() is essentially the concise identical to !isset($var) || $var == false.

Technical Details

PHP Version: 4.0+
Return Type: Boolean
Return Value: FALSE if the variable exists and isn’t empty, TRUE otherwise
PHP Changelog: PHP 5.5: it supports expressions, not only variables, and in PHP 5.4: Non-numeric offsets of strings, it returns TRUE

PHP empty() Function Example

Program:1

Variable 'x' is empty.
Variable 'x' is set
Program: 2

PHP 5.4 changes how empty() behaves when passed string offsets.

true
false
false
false
true
true
Program:3

This line is printed, because the $myvar1 is empty.
This line is printed, because the $myvar2 is empty.
This line is printed, because the $myvar3 is empty.
This line is printed, because the $myvar4 is empty.
This line is printed, because the $myvar5 is empty.
.
Important Note: This function doesn’t generate a warning if the variable doesn’t exist. which means that empty() is identical or equivalent to !isset($var) || $var == false.

Conclusion:

In this article, you have learned PHP empty() function with the different example. I hope you will enjoy it!. if have any query related program then contact me at info@tutorialscan.com I will try to resolve the problem. Stay healthy, stay safe! Happy coding! enjoy it!