Last active
February 7, 2018 09:29
-
-
Save duzun/e92e83dafbbd72dcb8db623a7653c7a8 to your computer and use it in GitHub Desktop.
Find a value in an array by key recursively
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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