note 19564 added to function.array-search

From: Date: Mon, 04 Mar 2002 09:03:11 +0000
Subject: note 19564 added to function.array-search
Groups: php.notes 
Request: Send a blank email to php-notes+get-27308@lists.php.net to get a copy of this message
Do not expect array_search() to return TRUE or FALSE like in_array(). if ($id = array_search($needle, $array)) ... Note that if the corresponding key of the value is 0 (the first element of an array), the value is found, but the function returns 0. So, use isset() for the given key like in the following example: $myarray = array(4, 8, 10); $array2check = array(4, 9); foreach ($array2check as $k=>$v) { $id = array_search($v, $myarray); if (isset($id)) { echo "$v found: \$myarray[$id]\n"; } } $id is undefined if array_search() returns FALSE, so you don't have to unset it at the end of the foreach() cycle. P.S.: The example above can be used instead of array_diff() which was broken, I don't know the reasons why. -- http://www.php.net/manual/en/function.array-search.php http://master.php.net/manage/user-notes.php?action=edit+19564 http://master.php.net/manage/user-notes.php?action=delete+19564 http://master.php.net/manage/user-notes.php?action=reject+19564

« previous php.notes (#27308) next »