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

How to check if an array is empty in php

PHPz
PHPzOriginal
2023-04-20 15:08:071036browse

When we process data, we often need to check whether the array is empty. In PHP, there are multiple ways to check if an array is null. These methods are described below.

The first method is to use the count() function. This function is used to return the number of elements in an array. If the number is 0, it means the array is empty. The code is as follows:

$array = array();
if (count($array) == 0) {
    echo '数组为空值';
} else {
    echo '数组不为空值';
}

The second method is to use the empty() function. This function is used to check whether a value is null, including empty string, 0, '0', null, false, array(). The code is as follows:

$array = array();
if (empty($array)) {
    echo '数组为空值';
} else {
    echo '数组不为空值';
}

The third method is to use the isset() function. This function is used to check whether a variable has been set, if the variable is set, it returns true, otherwise it returns false. The code is as follows:

$array = array();
if (isset($array) && count($array) > 0) {
    echo '数组不为空值';
} else {
    echo '数组为空值';
}

The fourth method is to use the array_filter() function. This function is used to filter empty elements in an array. The code is as follows:

$array = array('', 'a', 'b', null, false, 0);
$result = array_filter($array);
if (count($result) > 0) {
    echo '数组不为空值';
} else {
    echo '数组为空值';
}

All the above four methods can be used to check whether the array is empty, but in actual use, you should choose the method most suitable for the current situation.

The above is the detailed content of How to check 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