note 40933 added to function.array-search

From: Date: Tue, 23 Mar 2004 19:10:57 +0000
Subject: note 40933 added to function.array-search
Groups: php.notes 
Request: Send a blank email to php-notes+get-67069@lists.php.net to get a copy of this message
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); ?> ---- Manual Page -- http://www.php.net/manual/en/function.array-search.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+40933 Delete -- http://master.php.net/manage/user-notes.php?action=delete+40933&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+40933&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#67069) next »