Search Multidimensional Array in PHP

If you’re using PHP 5.1 or newer, this little function is for you! It’ll search multidimensional array’s and return the top level key so you can pull the data.

Searching a multidimensional array and returning one key

function recursiveArraySearch($haystack, $needle, $index = null)
{
$aIt = new RecursiveArrayIterator($haystack);
$it = new RecursiveIteratorIterator($aIt);
while($it->valid())
{
if (((isset($index) AND ($it->key() == $index)) OR (!isset($index))) AND ($it->current() == $needle)) {
return $aIt->key();
}
$it->next();
}
return false;
}
$key = recursiveArraySearch($_ARRAY_TO_SEARCH, 'Value_To_Search');

That will return one key.

 

Searching a multidimensional array and returning multiple keys

function recursiveArraySearch($haystack, $needle, $index = null)
{
$aIt = new RecursiveArrayIterator($haystack);
$it = new RecursiveIteratorIterator($aIt);
while($it->valid())
{
if (((isset($index) AND ($it->key() == $index)) OR (!isset($index))) AND ($it->current() == $needle)) {
$FoundKeys[] = $aIt->key();
}
$it->next();
}
return $FoundKeys;
}
$keys = recursiveArraySearch($_ARRAY_TO_SEARCH, 'Value_To_Search');

That will return multiple keys.