note 98065 added to function.array-search

From: Date: Mon, 24 May 2010 09:45:02 +0000
Subject: note 98065 added to function.array-search
Groups: php.notes 
Request: Send a blank email to php-notes+get-169549@lists.php.net to get a copy of this message
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; } ?> ---- Server IP: 69.147.83.197 Probable Submitter: 109.126.10.178 ---- Manual Page -- http://www.php.net/manual/en/function.array-search.php Edit -- https://master.php.net/note/edit/98065 Del: integrated -- https://master.php.net/note/delete/98065/integrated Del: useless -- https://master.php.net/note/delete/98065/useless Del: bad code -- https://master.php.net/note/delete/98065/bad+code Del: spam -- https://master.php.net/note/delete/98065/spam Del: non-english -- https://master.php.net/note/delete/98065/non-english Del: in docs -- https://master.php.net/note/delete/98065/in+docs Del: other reasons-- https://master.php.net/note/delete/98065 Reject -- https://master.php.net/note/reject/98065 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#169549) next »