Go4Expert (http://www.go4expert.com/)
-   PHP (http://www.go4expert.com/articles/php-tutorials/)
-   -   Recursive Array Item Count (http://www.go4expert.com/articles/recursive-array-item-count-t2801/)

Recursive Array Item Count

Sometimes we need to find the number of items, located inside an array.Let's take this array as example,
PHP Code:

``` \$a[0]=1;  \$a[1][0]=3;  \$a[1][1]=4;  \$a[3]=5;  ```
here the total item count is 4, but when you use count() function you get 3. So I wrote a small function which counts array elements, even recursively.

PHP Code:

``` function get_array_recursive_count(&\$a)  {      \$c = 0;      foreach(\$a as \$v)      {          if(is_array(\$v))              \$c += get_array_recursive_count(\$v);          else              \$c++;      }        return \$c;  }  ```
Example:
PHP Code:

``` \$aa = array("a","b");  \$bb = array("3","4");  \$a = array(\$aa,\$bb,"a");    function get_array_recursive_count(&\$a)  {      \$c = 0;      foreach(\$a as \$v)      {          if(is_array(\$v))              \$c += get_array_recursive_count(\$v);          else              \$c++;      }        return \$c;  }    print get_array_recursive_count(\$a);  print "<br/>";  print count(\$a);  ```
Output:
Code:

``` 5  3```

 All times are GMT +5.5. The time now is 18:11.