Skip to content

Instantly share code, notes, and snippets.

@duzun
Last active February 7, 2018 09:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save duzun/e92e83dafbbd72dcb8db623a7653c7a8 to your computer and use it in GitHub Desktop.
Save duzun/e92e83dafbbd72dcb8db623a7653c7a8 to your computer and use it in GitHub Desktop.
Find a value in an array by key recursively
<?php
// Note:
// Whether $list contains a NULL value for $needle at some level, or there is no $needle at all,
// in both cases this function returns NULL.
// If you want to find non-NULL $needle only, replace `array_key_exists` with `isset`
function findByKey($list, $needle) {
$stack = [$list];
while( !empty($stack) ) {
$list = array_shift($stack);
if ( array_key_exists($needle, $list) ) return $list[$needle];
foreach($list as $k => $l) if ( is_array($l) ) $stack[] = $l;
}
}
// This version is faster, but traversation order is changes (deepest first)
function findByKeyR($list, $needle) {
$stack = [$list];
while( !empty($stack) ) {
$list = array_pop($stack);
if ( array_key_exists($needle, $list) ) return $list[$needle];
foreach($list as $k => $l) if ( is_array($l) ) $stack[] = $l;
}
}
<?php
// Recursive version of the above
function findByKeyRec($list, $needle, &$found=NULL) {
if ( $found = array_key_exists($needle, $list) ) return $list[$needle];
foreach($list as $k => $l) if ( is_array($l) ) {
$r = findByKeyRec($l, $needle, $found);
if ( $found ) return $r;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment