note 98065 added to function.array-search

i
Newsgroups php.notes
Message-ID <[email protected]>
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
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.