tags:

views:

62

answers:

2

We gave a given array which can be in 4 states.

array has values that are:

  • only arrays
  • only non-arrays
  • both array and non array
  • array has no values
+2  A: 

Considering than an array-key can only be a numerical or string value (and not an array), I suppose you want to know about array-values ?

If so, you'll have to loop over your array, testing, for each element, if it's an array or not, keeping track of what's been found -- see the is_array function, about that.

Then, when you've tested all elements, you'll have to test if you found arrays, and/or non-array.


Something like this, I suppose, might do the trick :

$has_array = false;
$has_non_array = false;

foreach ($your_array as $element) {
    if (is_array($element)) {
        $has_array = true;
    } else {
        $has_non_array = true;
    }
}

if ($has_array && $has_non_array) {
    // both
} else {
    if ($has_array) {
        // only arrays
    } else {
        // only non-array
    }
}

(Not tested, but the idea should be there)


This portion of code should work for the three first points you asked for.

To test for "array has no value", The fastest way is to use the empty() language construct before the loop -- and only do the loop if the array is not empty, to avoid any error.

You could also count the number of elements in the array, using the count() function, and test if it's equal to 0, BTW.

Pascal MARTIN
+1  A: 

Some precalculation:

function isArray($reducedValue, $currentValue) {
    // boolean value is converted to 0 or 1
    return $reducedValue + is_array($currentValue);
}

$number_of_arrays = array_reduce($array, 'isArray', 0);

Then the different states can be evaluated as follows:

  1. only arrays

    count($array) == $number_of_arrays
    
  2. only non-arrays

    $number_of_arrays == 0
    
  3. both array and non array keys

    count($array) != $number_of_arrays
    
  4. array has no keys

     empty($array);
    

So you just need to write a function that returns the appropriate state.

Reference: in_array, array_reduce, empty

Felix Kling