Note Submitter: i [at] nemoden [dot] com
----
Gulio's function seems to meet my needs, but part of our project is still in PHP4, so I decided to write my own function that should respect backward compatibility with PHP4 and tuned the function a little so it could return an array of keys.
<?php
/**
* This function is an implementation of recursive array search<br />
* It returns corresponding key on success<br />
* If return flag is set to true, all keys will be returned as an array<br />
*
* <strong>Example</strong>:<br />
* $arr = array('a'=>'2','b'=>array('y'=>'r','t'=>'s'),'v'=>'1','g'=>'2', 't'=>array('1','0'), 'r'=>array('e'=>array('n','s'), 'q'=>array('p'=>'1')));<br />
* var_export(recursiveArraySearch($arr, 1));<br />
* will output <blockquote><hr />'v'<hr /></blockquote>
* var_export(recursiveArraySearch($arr, 1, true));<br />
* will output <blockquote><hr />array ( 0 => 'v', 1 => 't', 2 => 'r', )<hr /></blockquote>
*
* @author Kirill "Nemoden" K
* @param array $haystack
* @param mixed $needle
* @param bool $returnAll optional. Default is false
* @return index or false on failure
*/
function recursiveArraySearch($haystack, $needle, $returnAll = false) {
$a = array();
while (list($k,$v)=each($haystack)) {
if ($needle == $v || (is_array($v) && in_array($needle, $v))) {
if (!$returnAll)
return $k;
else
$a[] = $k;
}
else if (is_array($v)){
if ((bool)recursiveArraySearch($v,$needle, false)) {
if (!$returnAll)
return $k;
else
$a[] = $k;
}
}
}
if (sizeof($a))
return $a;
return false;
}
?>
lmpx.com only provides a reader for public news (NNTP) servers. It is not
affiliated with the servers or forums shown here and is not responsible for
the content of articles, which is written by their respective authors.