欢迎访问宙启技术站
智能推送

PHPempty()函数的用法及示例

发布时间:2023-06-21 23:24:40

The empty() function in PHP is a language construct that is used to determine whether a variable is empty or not. It returns a Boolean value – true if a variable is empty, and false if it is not. In this article, we’ll discuss the syntax and usage of the empty() function in PHP with the help of examples.

Syntax of empty() Function in PHP

The empty() function has the following syntax:

empty($variable);

where $variable is the variable whose emptiness we want to test.

Usage of empty() Function in PHP

The empty() function is commonly used to check whether a variable is set or not. In PHP, a variable is considered empty if it has one of the following values:

1. NULL

2. 0 (integer)

3. 0.0 (float)

4. “” (empty string)

5. “0” (string containing 0)

If the variable has any other value besides these, it is considered not empty.

Examples

Now let’s take a look at some examples that demonstrate the usage of empty() function:

Example #1: Check whether a variable is empty or not

In this example, we’ll create a variable $name and check whether it is empty or not using the empty() function.

<?php
$name = "";

if (empty($name)) {
    echo "The variable is empty.";
} else {
    echo "The variable is not empty.";
}
?>

Output:

The variable is empty.

Explanation: The $name variable is initialized with an empty string. When we pass this variable to the empty() function, it returns true since an empty string is considered as ‘empty’. Hence, the output is “The variable is empty”.

Example #2: Check whether a variable is set or not

In this example, we’ll create a variable $age and check whether it is set or not using the empty() function.

<?php
if (empty($age)) {
    echo "The variable is not set.";
} else {
    echo "The variable is set.";
}
?>

Output:

The variable is not set.

Explanation: The $age variable is not initialized with any value. When we pass this variable to the empty() function, it returns true since the variable is not set. Hence, the output is “The variable is not set”.

Example #3: Check whether a string is empty or not

In this example, we’ll create a string $message and check whether it is empty or not using the empty() function.

<?php
$message = "Hello, world!";

if (empty($message)) {
    echo "The string is empty.";
} else {
    echo "The string is not empty.";
}
?>

Output:

The string is not empty.

Explanation: The $message string is initialized with the value “Hello, world!”. When we pass this string to the empty() function, it returns false since a non-empty string is considered as ‘not empty’. Hence, the output is “The string is not empty”.

Conclusion

In this article, we discussed the syntax and usage of the empty() function in PHP with the help of examples. We saw that the empty() function can be used to check whether a variable is empty or not, or whether it is set or not. It is a useful tool for conditional statements in PHP programming.