note 40933 deleted from function.array-search by nlopess
| From: | nlopess@php.net | Date: | Tue, 23 Mar 2004 19:51:32 +0000 |
| Subject: | note 40933 deleted from function.array-search by nlopess | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-67071@lists.php.net to get a copy of this message | ||
Note Submitter: fierojoe@fierojoe.com
----
I could not find a good way to search an array of associative arrays and return the key of the found
array, so I created this function to do it. It's very handy to search 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);
?>