Wednesday, January 2, 2013

Recursively Find All Array Keys In A Multi-Dimensional Array In PHP

<?php

$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 array_keys_recursive($arr,&$rKeys = array())
{
 foreach ($arr as $key => $val)
 {
  if(is_array($val))
  {
   $rKeys[] = $key;
   array_keys_recursive($val,$rKeys);
  }  
 }
 return $rKeys;
}
print_r( array_keys_recursive($tmpArray) );

//Echos:
//Array
//(
//    [0] => root
//    [1] => a
//    [2] => b
//    [3] => c
//    [4] => d
//    [5] => 99
//    [6] => cucumber
//    [7] => user
//)
?>