Miloš Đakonović
Miloš Đakonović

Reputation: 3871

How to get exact number of array elements(members)in PHP?

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?

Upvotes: 1

Views: 659

Answers (2)

Carlos
Carlos

Reputation: 5072

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;
}

Upvotes: 1

xdazz
xdazz

Reputation: 160853

You could use array_walk_recursive.

$count = 0; 
array_walk_recursive($arr, function($var) use (&$count) { 
  $count++; 
}); 
echo $count; 

The working demo.

Upvotes: 6

Related Questions