Home  >  Article  >  Backend Development  >  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 11:37:591156browse

In PHP, to determine whether an array is empty, you can use the following method.

Method 1: Use the empty() function

The empty() function can detect whether a variable is empty. If the variable is undefined, null, false, 0 or an empty string, it will return true. Therefore, you can use the empty() function to detect whether an array is empty.

Sample code:

$arr = array();

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

Output result:

数组为空

Method 2: Use the count() function

The count() function can return the elements in an array number, if the array is empty, 0 is returned. Therefore, you can use the count() function to determine whether the array is empty.

Sample code:

$arr = array();

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

Output result:

数组为空

Method 3: Use isset() function

isset() function can detect whether a variable has been defined and not null. If a variable is undefined or null, the isset() function returns false. Therefore, you can use the isset() function to detect whether the array is empty.

Sample code:

$arr = array();

if (!isset($arr[0])) {
    echo '数组为空';
} else {
    echo '数组不为空';
}

Output result:

数组为空

In summary, the above three methods can be used to determine whether an array is empty. The most commonly used method is to use empty() function.

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