note 40932 deleted from function.in-array by felipe

[email protected]
Newsgroups php.notes
Message-ID <[email protected]>
Note Submitter: fierojoe at fierojoe dot com 

----

I couldn't find an easy way to search an array of associative arrays and return the key of the found associative array, so I created this little function to do it for me. Very handy for searching through the results of a mysql_fetch_assoc()

<?php

$a = array(
  array('id' => 1, 'name' => 'oranges'),
  array('id' => 2, 'name' => 'apples'),
  array('id' => 3, 'name' => 'coconuts'),
);

function _array_search($s, $a) {
  for($i=0; $i <= count($a); $i++) {
    if (in_array($s, $a[$i])) {
      return($i);
      break;
    }
  }
  return(FALSE);
}

//returns key 0 for the second element, 'id' => 1
  echo _array_search(1, $a);

//returns key 2 for the second element, 'id' => 3
  echo _array_search(3, $a);

//returns key 1 for the second element, 'id' => 2
  echo _array_search(2, $a);

?>
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.