• PHP Video Tutorials

PHP - empty() Function



Definition and Usage

The empty() function checks whether a variable is empty.

Syntax

bool empty ( mixed $var )

Parameters

Sr.No Parameter & Description
1

var

Variable to be checked.

*mixed: mixed indicates that a parameter may accept multiple (but not necessarily all) types

Return Values

This function returns −

  • true − if the variable is empty

  • false − if variable exists or has a non-empty or non-zero value

The following values evaluates to empty −

  • integer − if value is 0 then empty() returns true. For any other value returns false.

  • float − if value is 0.0 then empty() returns true. For any other value returns false.

  • string − if string value is "0" and null ("") then empty() returns true. For any other value returns false (even "0.0").

  • array − if value is empty array() then boolval() returns true. For any other value returns false.

  • NULL − empty() always returns false when variable is NULL.

  • Boolean − if boolean variable is FALSE then empty() returns true.

Dependencies

PHP 4.0 and above. Prior to PHP 5.5, empty() only supports variables; anything else will result in a parse error.

Example

Following example demonstrates return values with different types of variables −

<?php
   // PHP program demo for empty() function

   echo 'when var is 0 function empty() returns <b>'.( empty( 0 )? 'true' : 'false').'</b>';
   echo 'when var is "0.0" function empty() returns <b>'.( empty( "0.0" )? 'true' : 'false').'</b>';
   echo 'when var is "0" function empty() returns <b>'.( empty( "0" )? 'true' : 'false').'</b>';
   echo 'when var is "" function empty() returns <b>'.( empty( "" )? 'true' : 'false').'</b>';
   echo 'when var is [] function empty() returns <b>'.( empty( [] )? 'true' : 'false').'</b>';
   echo 'when var is NULL function empty() returns <b>'.( empty( NULL )? 'true' : 'false').'</b>';
   echo 'when var is FALSE function empty() returns <b>'.( empty( FALSE )? 'true' : 'false').'</b>';
?>

Output

This will produce following result −

when var is 0 function empty() returns true
when var is "0.0" function empty() returns false
when var is "0" function empty() returns true
when var is "" function empty() returns true
when var is [] function empty() returns true
when var is NULL function empty() returns true
when var is FALSE function empty() returns true
php_variable_handling_functions.htm
Advertisements