```If `$arr` is an empty array, the above code will lose"/> ```If `$arr` is an empty array, the above code will lose">

Home  >  Article  >  Backend Development  >  [Organization and Sharing] Several ways to determine whether an array is empty in PHP

[Organization and Sharing] Several ways to determine whether an array is empty in PHP

PHPz
PHPzOriginal
2023-04-12 09:20:45542browse

In PHP, there are many ways to determine whether an array is empty. This article will introduce you to several methods in PHP to determine whether an array is empty.

Method 1: Use the empty() function

<?php
$arr = array(); // 空数组
if (empty($arr)) {
    echo "数组为空";
} else {
    echo "数组不为空";
}
?>

If $arr is an empty array, the above code will output:

数组为空

If ## If there are elements in #$arr, the output will be:

数组不为空
Method 2: Use count() function

<?php
$arr = array(); // 空数组
if (count($arr) == 0) {
    echo "数组为空";
} else {
    echo "数组不为空";
}
?>

If

$arr is an empty array, the above The code will output:

数组为空
If there are elements in

$arr, then it will output:

数组不为空
Method 3: Use isset() function

<?php
$arr = array(); // 空数组
if (isset($arr) && count($arr) > 0) {
    echo "数组不为空";
} else {
    echo "数组为空";
}
?>

If

$arr is an empty array, the above code will output:

数组为空
If there are elements in

$arr, then output:

数组不为空
Method 4 : Use the array_key_exists() function

<?php
$arr = array(); // 空数组
if (array_key_exists(0, $arr)) {
    echo "数组不为空";
} else {
    echo "数组为空";
}
?>

If

$arr is an empty array, the above code will output:

数组为空
If there is one in

$arr element, the output is:

数组不为空
Summary

The above is the method to determine whether the array is empty in PHP. Which method to use depends on your code needs. If you only need to determine whether an array is empty, it is recommended to use the empty() function. If you need to count the number of elements in an array, use the count() function. If you need to check whether a variable already exists and is not empty, use the isset() function. If you need to determine whether an array is empty based on whether a specified key exists in the array, use the array_key_exists() function.

The above is the detailed content of [Organization and Sharing] Several ways to determine whether 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