在php中检查数组是否为null

时间:2011-11-09 16:34:05

标签: php arrays null

我有一个如下所示的数组,它是通过解析xml url生成的。

数组是

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

    )
  )

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

6 个答案:

答案 0 :(得分:32)

你可以使用

empty($result) 

检查主阵列是否为空。

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

例如:

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

答案 1 :(得分:3)

纠正;

/*
 return true if the array is not empty
 return false if it is empty
*/
function is_array_empty($arr){
  if(is_array($arr)){     
      foreach($arr as $key => $value){
          if(!empty($value) || $value != NULL || $value != ""){
              return true;
              break;//stop the process we have seen that at least 1 of the array has value so its not empty
          }
      }
      return false;
  }
}

答案 2 :(得分:2)

this check if array is empty 

    if (!empty($result) {
       // do stuf if array is not empty
    }else{

      // do stuf if array is empty
    }

this check array is null or not


 if (is_null($result) {
       // do stuf if array is null
    }else{

      // do stuf if array is not null
}

答案 3 :(得分:2)

^ _ ^

之前两个ppl的正确代码
/* return true if values of array are empty
*/
function is_array_empty($arr){
   if(is_array($arr)){
      foreach($arr as $value){
         if(!empty($value)){
            return false;
         }
      }
   }
   return true;
}

答案 4 :(得分:1)

我明白你想要什么。如果所有数据都为空或至少1不为空,则需要检查数组的每个数据

清空数组

阵   (  [Tags] => SimpleXMLElement对象     (         [0] =>     )   )

不是空数组

阵   (  [Tags] => SimpleXMLElement对象     (         [0] =>,[1] => “S”     )   )


我希望我是对的。如果数组中至少有一个数据具有值,则可以使用此函数检查数组的每个数据。

/*
 return true if the array is not empty
 return false if it is empty
*/
function is_array_empty($arr){
  if(is_array($arr)){     
      foreach($arr $key => $value){
          if(!empty($value) || $value != NULL || $value != ""){
              return true;
              break;//stop the process we have seen that at least 1 of the array has value so its not empty
          }
      }
      return false;
  }
}

if(is_array_empty($result['Tags'])){
    //array is not empty
}else{
    //array is empty
}

希望有所帮助。

答案 5 :(得分:1)

如果数组看起来像这样[null]或[null,null]或[null,null,null,...]

你可以使用implode:

implode用于将数组转换为字符串。

if(implode(null,$arr)==null){
     //$arr is empty
}else{
     //$arr has some value rather than null
}
相关问题