note 98065 deleted from function.array-search by danbrown

From: Date: Mon, 24 May 2010 14:05:04 +0000
Subject: note 98065 deleted from function.array-search by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-169559@lists.php.net to get a copy of this message
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; } ?>

« previous php.notes (#169559) next »