Extract all keys from a multidimensional array

Although PHP boasts a huge number of array related functions, unfortunately there is no native function to extract keys from a multidimensional array because array_keys only supports one-dimensional arrays.

For those occasions when you need it, array_keys_multi might help you.

Let's look at the function first:

  1. <?php
  2.  
  3. /**
  4.  * Get list of all keys of a multidimentional array
  5.  *
  6.  * @param array $array Multidimensional array to extract keys from
  7.  * @return array
  8.  */
  9. function array_keys_multi(array $array)
  10. {
  11.     $keys = array();
  12.  
  13.     foreach ($array as $key => $value) {
  14.         $keys[] = $key;
  15.  
  16.         if (is_array($value)) {
  17.             $keys = array_merge($keys, array_keys_multi($value));
  18.         }
  19.     }
  20.  
  21.     return $keys;
  22. }

As you can see the function accepts only one parameter and it must be an array.

Next we instantiate the final list of keys as an empty array and start iterating through each item in the $array variable.

We add the current item key to the final list of keys. If the current item value is an array itself then we execute array_keys_multi on that array and add its keys to our final $keys array.

When every item is checked, we return the list of keys.

That's all folks!

If you want to know more about recursion, there is a good article on Zend Devzone - Recursion In PHP: Tapping Unharnessed Power.

Comments
1
Thanks! Huge help, I was trying all of the array_unique, array_keys functions
William Isted, January 19th 2012, 15:16
2
Thank you so much!!!
chakravarthy, November 16th 2013, 13:33
Name
Email (required)
will not be published
Website
Recaptcha
you will only be required to fill it in once in this session

You can use [code][/code] tags in your comments