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
Release: 2023-04-19 14:04:57
Original
1320 people have browsed it

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 '数组不为空';
}
Copy after login

Output result:

数组为空
Copy after login
Copy after login
Copy after login

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 '数组不为空';
}
Copy after login

Output result:

数组为空
Copy after login
Copy after login
Copy after login

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 '数组不为空';
}
Copy after login

Output result:

数组为空
Copy after login
Copy after login
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template