note 32883 added to function.array-search

From: Date: Tue, 10 Jun 2003 00:50:20 +0000
Subject: note 32883 added to function.array-search
Groups: php.notes 
Request: Send a blank email to php-notes+get-50069@lists.php.net to get a copy of this message
If you are using the result of array_search in a condition statement, make sure you use the === operator instead of == to test whether or not it found a match. Otherwise, searching through an array with numeric indicies will result in index 0 always getting evaluated as false/null. This nuance cost me a lot of time and sanity, so I hope this helps someone. In case you don't know what I'm talking about, here's an example: $code = array("a", "b", "a", "c", "a", "b", "b"); // infamous abacabb mortal kombat code :-P // this is WRONG while (($key = array_search("a", $code)) != NULL) { // infinite loop, regardless of the unset unset($code[$key]); } // this is _RIGHT_ while (($key = array_search("a", $code)) !== NULL) { // loop will terminate unset($code[$key]); } ---- Manual Page -- http://www.php.net/manual/en/function.array-search.php Edit Note -- http://master.php.net/manage/user-notes.php?action=edit+32883 Delete Note -- http://master.php.net/manage/user-notes.php?action=delete+32883&report=yes Reject Note -- http://master.php.net/manage/user-notes.php?action=reject+32883&report=yes

« previous php.notes (#50069) next »