Say I have an array like this:
array('a string', 23, array(array('key'=>'value'), 67, 'another string'), 'something else')
and I want to know how many values my array has, excluding arrays that are member of the main array. How? (The expected result is 6)
Foreach loop is not suitable because of the problem itself - unknown depth of array.
Does anyone know how to implement this?
You could use array_walk_recursive.
$count = 0;
array_walk_recursive($arr, function($var) use (&$count) {
$count++;
});
echo $count;
Following function returns the number of all non-array values within a given array -- despite it is multidimensional or not.
function countNonArrayValues(array $array)
{
$count = 0;
foreach ($array as $element) {
$count += is_array($element) ? countNonArrayValues($element) : 1;
}
return $count;
}