Search a Multi-dimensional Array for a Key

It’s not every day that one needs to search a multi-dimensional array for a key, and return the associated value, but a simple recursive function allows such an action. In a project I was working on recently, I needed to check the status of a record, but the status array was segmented into three main categories.

So I wrote a quick recursive function to handle the task. Please note, the function will only work if all keys are different. No two keys in the multi-dimensional array can be the same! Yes, I said it twice, but to emphasize that it matters.

if( ! function_exists('array_key_search_recursive') )
{
  /**
   * Given a need to search through a multi-dimensional array for a key's 
   * value, when the key is know, and no 2 keys have the same name,
   * this function will return the associated value.
   */
  function array_key_search_recursive( $needle, $haystack )
  {
    foreach( $haystack as $k => $v )
    {
      if( $needle === $k )
      {
        return $v;
      }
      else if( is_array( $v ) && array_key_search_recursive( $needle, $v ) !== FALSE )
      {
        return array_key_search_recursive( $needle, $v );
      }
    }

    return FALSE;
  }
}
Posted in PHP