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-20 13:48:45985browse

When we use PHP arrays, sometimes we need to judge whether the array is empty. In PHP, there are many ways to determine whether an array is empty. This article introduces three of them.

Method 1:

Use the count() function to determine whether the array is empty. The count() function can return the number of elements in an array. When there are no elements in the array, the count() function returns 0, so you can use the count() function to determine whether an array is empty.

Code example:

<?php
    $arr = array(); // 定义一个空数组
    if (count($arr) == 0) { // 判断数组是否为空
        echo "这个数组是空的";
    } else {
        echo "这个数组不是空的";
    }
?>

Method 2:

Use the empty() function to determine whether the array is empty. The empty() function is used to check whether a variable is empty, but this function can also be used to determine whether an array is empty. The empty() function returns true when there are no elements in the array.

Code example:

<?php
    $arr = array(); // 定义一个空数组
    if (empty($arr)) { // 判断数组是否为空
        echo "这个数组是空的";
    } else {
        echo "这个数组不是空的";
    }
?>

Method three:

Use the array_key_exists() function to determine whether the array is empty. The array_key_exists() function is used to determine whether a given key exists in an array. If an array is empty, it will not have any keys, so you can use this function to determine whether an array is empty.

Code example:

<?php
    $arr = array(); // 定义一个空数组
    if (!array_key_exists(0, $arr)) { // 判断数组是否为空
        echo "这个数组是空的";
    } else {
        echo "这个数组不是空的";
    }
?>

The above is an introduction to three methods to determine whether a PHP array is empty. I hope it will be helpful to everyone's learning.

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