Skip to content

Instantly share code, notes, and snippets.

@mbenegas
Last active April 21, 2016 20:19
Show Gist options
  • Select an option

  • Save mbenegas/8251530 to your computer and use it in GitHub Desktop.

Select an option

Save mbenegas/8251530 to your computer and use it in GitHub Desktop.
Find value in multidimensional array.
<?php
function find($criteria, $array, &$match){
$found = array_key_exists($criteria, $array);
if ($found === false){
foreach ($array as $value){
if (is_array($value)){
if (!find($criteria, $value, $match)){
continue;
} else {
return true;
}
}
}
return false;
} else {
$match = $array[$criteria];
return true;
}
}
$array = array(array('1' => array('a', 'b' => array('i', 'ii')), '2', '3'),
array('4' => array('z', 'zz' => 'multidimensional array value'), '5', '6'));
$testArray = array('z', 'zz' => 'test value');
$matches = null;
$test = find('zz', $testArray, $matches);
var_dump($test, 'test');
var_dump($matches, 'match');
$found = find('zz', $array, $matches);
var_dump($found, 'found');
var_dump($matches, 'match');
@mbenegas
Copy link
Author

mbenegas commented Jan 4, 2014

You can find a working version at http://codepad.org/BFxPnOAZ

@wagagt
Copy link

wagagt commented Jan 4, 2014

Excellent!

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