Array Search Function


/ Published in: PHP
Save to your folder(s)

Functions to search from arrays as well as recursive arrays.


Copy this code and paste it in your HTML
  1. // search from array
  2. function array_query($array,$what){
  3. if(in_array($what, $array)){
  4. return $array[array_search($what, $array)];
  5. }
  6. return false;
  7. }
  8.  
  9.  
  10. // search from recursive arrays
  11. function recursiveArraySearch($haystack, $needle, $index = null)
  12. {
  13. $aIt = new RecursiveArrayIterator($haystack);
  14. $it = new RecursiveIteratorIterator($aIt);
  15.  
  16. while($it->valid())
  17. {
  18. if (((isset($index) AND ($it->key() == $index)) OR (!isset($index))) AND ($it->current() == $needle)) {
  19. return $aIt->key();
  20. }
  21.  
  22. $it->next();
  23. }
  24.  
  25. return false;
  26. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.