Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php recursive array counting

I'm trying to write a function which counts array elements recursively.

But result is false.

What could it be problem?

$schema = array(
    'div' => array(
        'class' => 'lines',
        'div' => array(
             'span' => array(
                'key' => 'Product Name'
            ),
            'val' => 'Soap'
        ),
        'layer' => array(
             'span' => array(
                'key' => 'Product Name'
            ),
            'val' => 'Ball'
            )
        )
);

function count_r($array, $i = 0){
    foreach($array as $k){
        if(is_array($k)){ $i += count_r($k, count($k)); }
        else{ $i++; }
    }
    return $i;
}

echo count_r($schema);
like image 915
Deniz Porsuk Avatar asked Aug 25 '13 14:08

Deniz Porsuk


People also ask

How do I count items in an array PHP?

You can simply use the PHP count() or sizeof() function to get the number of elements or values in an array. The count() and sizeof() function returns 0 for a variable that has been initialized with an empty array, but it may also return 0 for a variable that isn't set.

How do you count elements in an array?

//Number of elements present in an array can be calculated as follows. int length = sizeof(arr)/sizeof(arr[0]);

How do you count numbers in PHP?

PHP | count() Function. This inbuilt function of PHP is used to count the current elements in the array. The function might return 0 for the variable that has been set to an empty array. Also for the variable which is not set the function returns 0.

What is the use of count () function in PHP?

The count() function returns the number of elements in an array.


2 Answers

This is the second result on Google so I'm adding this as a reference. There is already a built-in function in PHP that you can use: count().

You can use it like this:

count($schema, COUNT_RECURSIVE);

This function can also detect recursion to avoid infinite loops so it's safer than solutions in other answers.

like image 178
Christian P Avatar answered Oct 19 '22 07:10

Christian P


PHP has a built-in method for this purpose, called count(). If passed without any additional parameters, count() returns the number of array keys on the first level. But, if you pass a second parameter to the count method count( $schema, true ), then the result will be the total number of keys in the multi-dimensional array. The response marked as correct only iterates first and second level arrays, if you have a third child in that array, it will not return the correct answer.

This could be written as a recursive function, if you really want to write your own count() method, though.

like image 33
Sorin Gheata Avatar answered Oct 19 '22 06:10

Sorin Gheata