Home >Backend Development >PHP Problem >How to determine if an array is empty in php

How to determine if an array is empty in php

PHPz
PHPzOriginal
2023-04-19 09:16:21583browse

There are many methods to determine whether an array is empty in PHP. This article will introduce it to you in detail.

Method 1: Use empty() function

empty() is a very practical function in PHP, which can be used to determine whether a variable is empty. When its parameter is an array, it will determine whether the array is empty.

Sample code:

$arr1 = array();
if (empty($arr1)) {
    echo "arr1 是空的";
} else {
    echo "arr1 不是空的";
}

When there are no elements in $arr1, the output result is:

arr1 是空的

Note: If a key in an array exists but the corresponding If the value is empty (i.e. null, false, 0, empty string, etc.), empty() will still treat the array as empty.

Method 2: Use the count() function

The count() function is used to return the number of elements in the array. If an array does not have any elements, it returns a value of 0, which means the array is empty.

Sample code:

$arr2 = array();
if (count($arr2) == 0) {
    echo "arr2 是空的";
} else {
    echo "arr2 不是空的";
}

When there are no elements in $arr2, the output result is:

arr2 是空的

Note: Using the count() function is better than using empty() multiple times The function is more efficient because the count() function only needs to iterate through the array once.

Method 3: Use isset() function

isset() function is used to determine whether a variable is set and the variable is not null. It is also set if there are no elements in an array, so the isset() function cannot determine whether an array is empty.

Sample code:

$arr3 = array();
if (isset($arr3)) {
    echo "arr3 已设置";
} else {
    echo "arr3 未设置";
}

When there are no elements in $arr3, the output result is:

arr3 已设置

Note: The isset() function can only determine whether the variable is set, and It cannot be judged whether its value is null, so it is generally used to judge whether the variable exists.

Conclusion

In PHP, we can use the empty() function or count() function to determine whether an array is empty. The empty() function is used to determine whether there are elements in the array, and the count() function is used to determine the number of elements in the array. The isset() function cannot be used to determine whether an array is empty, it can only be used to determine whether a variable is set.

The above is the detailed content of How to determine if an array is empty in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn