检查php中的数组是否为空

2022-08-30 17:30:14

我有一个像下面这样的数组,它是通过解析xml url生成的。

数组是

Array
  (
 [Tags] => SimpleXMLElement Object
    (
        [0] => 

    )
  )

阵列名称为 。现在我想检查一下,如果数组像上面那样收到,我想打印一条失败的消息。但是如何在if条件下检查此数组?$result


答案 1

您可以使用

empty($result) 

以检查主数组是否为空。

但是,由于您有一个 SimpleXMLElement 对象,因此您需要查询该对象是否为空。查看 http://www.php.net/manual/en/simplexmlelement.count.php

前任:

if (empty($result)) {
    return false;
}
if ( !($result['Tags'] instanceof SimpleXMLElement)) {
    return false;
}
return ($result['Tags']->count());

答案 2

这将检查变量是否未设置或是否包含 falsey 值(零、空字符串、空数组等)

if (!empty($result) {
    // do stuff if the variable is not empty
} else {
    // do stuff if the variable is empty
}

这将检查变量是否为 null

if (is_null($result) {
   // do stuff if the variable is null
} else {
   // do stuff if the variable is not null
}