PHP空函数-关联数组

Bal*_*mal 1 php

谁能解释这为什么返回非空?

<?php

$attributes=array("description"=>"","quantity"=>"","price"=>"","discount"=>"");

if(empty($attributes))
   echo 'empty';
else
    echo 'non empty';
exit;

?>
Run Code Online (Sandbox Code Playgroud)

Ama*_*ali 5

从以下手册中获取empty()

确定一个变量是否被认为是空的。如果变量不存在或其值等于FALSE,则将其视为空。如果变量不存在,则empty()不会生成警告。

在这种情况下,变量$attributes存在并且不等于FALSE。因此empty()将返回boolean FALSE

要检查它们是否为空并回显一条消息:

foreach ($attributes as $key => $value) {
    if (empty($value)) {
        echo "'$key' is empty\n";
    }
}
Run Code Online (Sandbox Code Playgroud)

要检查所有数组值是否为空:

if(!array_filter($attributes)) {
    echo 'All values are empty';
}
Run Code Online (Sandbox Code Playgroud)

要检查任何数组值是否为空:

if (array_search('', $attributes) !== FALSE) {
    echo 'One of the values in the array is empty';
}
Run Code Online (Sandbox Code Playgroud)