Skip to content

Instantly share code, notes, and snippets.

@duzun

duzun/findByKey.php

Last active Feb 7, 2018
Embed
What would you like to do?
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