1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

Recursive Array Item Count

Discussion in 'PHP' started by pradeep, Feb 1, 2007.

  1. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,646
    Likes Received:
    86
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    Sometimes we need to find the number of items, located inside an array.Let's take this array as example,
    PHP:
    $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:
    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:
    $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
     

Share This Page