PHP 判断数组是否为空几种方式

| 选择喜欢的代码风格  

PHP 使用 empty() 函数


empty() 函数用于检查一个变量是否为空。对于数组来说,如果数组为空(即没有元素),empty() 会返回 true

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

PHP 使用 count() 函数


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

PHP 使用 is_array() 结合 empty()


如果需要确保变量是一个数组并且为空,可以结合 is_array()empty() 函数。

<?php
$array = [];
if (is_array($array) && empty($array)) {
    echo "变量是数组且为空";
} else {
    echo "变量不是数组或数组不为空";
}
 

PHP 使用 !isset()count()


如果需要确保数组存在且为空,可以结合 !isset() 和 count()。

<?php
$array = [];
if (!isset($array) || count($array) == 0) {
    echo "数组不存在或为空";
} else {
    echo "数组存在且不为空";
}
 

PHP 使用 array_filter()empty()


如果需要判断数组是否为空,同时忽略数组中的空值 nullfalse 等,可以使用 array_filter() 结合 empty()。

<?php
$array = [null, '', false];
if (empty(array_filter($array))) {
    echo "数组为空(忽略空值、null和false)";
} else {
    echo "数组不为空";
}
 

PHP 判断数组为空方式总结


  • 如果只是简单判断数组是否为空,推荐使用 empty() 或 count()
  • 如果需要更严格的类型检查,可以结合 is_array()
  • 如果需要忽略数组中的 null 和 false 等,可以使用 array_filter()

 

CommandNotFound ⚡️ 坑否 - 其他频道扩展阅读:




发表评论