Reputation: 29377
We gave a given array which can be in 4 states.
array has values that are:
Upvotes: 0
Views: 312
Reputation: 816232
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:
only arrays
count($array) == $number_of_arrays
only non-arrays
$number_of_arrays == 0
both array and non array keys
count($array) != $number_of_arrays
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
Upvotes: 1
Reputation: 400902
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.
$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)
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.
Upvotes: 2