empty() function is a built-in function in PHP that checks whether a variable is empty. A variable is considered empty if it does not exist, or if its value is equal to false, an empty string, 0, "0", null, or an empty array.
The syntax of the
empty() function is as follows:
bool empty(mixed $var)
The function takes a single parameter,
$var, which is the variable to be checked for emptiness. The function returns true if the variable is empty, and false otherwise.
Here is an example of how to use the
empty() function in PHP:
$var1 = ""; $var2 = "hello"; $var3 = null; $var4 = 0; $var5 = "0"; $var6 = array(); echo empty($var1) . "\n"; // output: 1 (true) echo empty($var2) . "\n"; // output: 0 (false) echo empty($var3) . "\n"; // output: 1 (true) echo empty($var4) . "\n"; // output: 1 (true) echo empty($var5) . "\n"; // output: 1 (true) echo empty($var6) . "\n"; // output: 1 (true)
In this example, we define six variables with different data types:
$var1 is an empty string,
$var2 is a non-empty string,
$var3 is null,
$var4 is 0,
$var5 is the string "0", and
$var6 is an empty array. We then use the
empty() function to check whether each variable is empty. The output shows that
$var6 are all empty (true), while
$var2 is not empty (false).
empty() function is a useful tool for checking whether a variable is empty in PHP. It can be used to avoid errors that may occur when working with empty variables or non-empty variables that are expected to contain data. By using this function, developers can ensure that their code is working with the correct data types and avoid errors that may occur when working with mixed data types.