Wednesday, January 2, 2013

Recursively Count Array Keys In A Multi-Dimensional Array In PHP

<?php
//Array With 8 Keys
$tmpArray = array (
  'root' => array (
    'a' => array(1,2,3,4,5),
    'b' => array(6,7,8,9,0),
    'c' => array(11,22,33,44,55),
    'd' => array(66,77,88,'99' => 
     array('apple','banana','cucumber'=> 
      array('alpha','beta','gamma'))
       )
      ),
  'user' => array('foo','bar')
    );
    
function num_array_keys_recursive($arr,$numKeys = 0)
{
 foreach ($arr as $key => $val)
 {
  if(is_array($val))
  {
   $numKeys ++;
   $numKeys = num_array_keys_recursive($val,$numKeys);
  }  
 }
 return $numKeys;
}
echo num_array_keys_recursive($tmpArray);
//Echos 8
?>

No comments:

Post a Comment