检查数组是否为空 [英] Check whether an array is empty

查看:63
本文介绍了检查数组是否为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码

<?php

$error = array();
$error['something'] = false;
$error['somethingelse'] = false;

if (!empty($error))
{
    echo 'Error';
}
else
{
    echo 'No errors';
}

?>

然而,empty($error) 仍然返回 true,即使什么都没有设置.

However, empty($error) still returns true, even though nothing is set.

哪里不对?

推荐答案

数组中有两个元素,这绝对不意味着数组为空.作为快速解决方法,您可以执行以下操作:

There are two elements in array and this definitely doesn't mean that array is empty. As a quick workaround you can do following:

$errors = array_filter($errors);

if (!empty($errors)) {
}

array_filter() 函数的默认行为将从数组中删除所有等于 null, 0, ''false.

array_filter() function's default behavior will remove all values from array which are equal to null, 0, '' or false.

否则在您的特定情况下,empty() 构造将始终返回 true,如果至少有一个元素具有空"值.

Otherwise in your particular case empty() construct will always return true if there is at least one element even with "empty" value.

这篇关于检查数组是否为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆