Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save wpscholar/6747565 to your computer and use it in GitHub Desktop.
Save wpscholar/6747565 to your computer and use it in GitHub Desktop.
Recursively traverses a multidimensional array in search of a specific key and returns an array containing the keys that correspond to the path of the first found instance, or an empty array on failure.
<?php
/**
* Recursively traverses a multidimensional array in search of a specific key and returns an
* array containing the keys that correspond to the path of the first found instance, or an
* empty array on failure.
*/
function recursive_multidimensional_array_search_by_key( $key, array $data, $stack = array() ) {
if( array_key_exists( $key, $data ) ) {
array_push( $stack, $key );
return $stack;
}
foreach ( $data as $k => $v ) {
if( is_array( $v ) ) {
array_push( $stack, $k );
$found = call_user_func( __FUNCTION__, $key, $v, $stack );
if( $found ) {
return $found;
}
array_pop( $stack );
}
}
return false;
}
@kklepper
Copy link

Thanks a lot! Saved my day. After my approach failed and some investigation, I could ask the proper question and found your solution.

@wpscholar
Copy link
Author

Awesome!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment