Hello

The function below checks if an element of array is empty. If it's empty, it will return true. But the function doesn't seem to work. Given an array as the following:

Array ( [Answer] => Array ( [9] => 3 [11] => 2 ) [Source] => Array ( [9] => [11] => 2 ) )

function is_array_empty($arr){
foreach ($arr as $key=>$value){
$element=$value;
if (gettype($element) == "array"){
return is_array_empty($element);
}else{
if (empty($value)){
return true;
}
}
}
}

Can someone help me?

Thanks.

Norman

    Try This code out

    $data = array ( 'Answer' => array ( 4 => 8, 11 => 3 ), 'Source' => array ( 9 => '', 11 => 2 ) );

    $ret_val = '';

    function is_array_empty($arr)
    {
    global $ret_val;

    foreach ($arr as $key => $value)
    {
    $element=$value;

      if (gettype($element) == "array")
      {
         is_array_empty($element);
    
      }  else
      {
         if (empty($value))
         {
            $ret_val = 'error : ' . $key;
            break;
         }
    
      }
    
      if($ret_val != '')
         break;

    }

    return $ret_val;
    }

    echo "Test : " . is_array_empty($data);

      I take it is_array_empty($array) should return true if $array has any empty
      elements or if any of its elements are is_array_empty() - and false otherwise?
      I notice your code never bothers to return false, which looks odd.

      function is_array_empty($arr)
      {
      	// Divide the array into subarrays and non-subarrays
      	$subarrays = array_filter($arr, 'is_array');
      	$scalars = array_diff($arr, $subarrays);
      
      // Weed out empty elements of $arr
      $nonempty_scalars = array_filter($scalars);
      // If elements were weeded out, they were empty
      if(count($nonempty_scalars)<count($scalars)) return true;
      // If there were no subarrays, then the array didn't have empty elements
      if(!count($subarrays)) return false;
      
      // Replace the subarrays with whether they're is_array_empty or not
      $subarrays = array_map('is_array_empty', $subarrays);
      // And filter out those that were
      $nonempty_subarrays = array_diff($subarrays, array_filter($subarrays));
      if(count($nonempty_subarrays)<count($subarrays)) return true;
      
      return false;
      }
      

      Maybe it's overpowered for your needs, but it appears to work.

        Write a Reply...