note 32883 modified in function.array-search by vrana

From: Date: Tue, 17 Aug 2004 14:49:04 +0000
Subject: note 32883 modified in function.array-search by vrana
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-80020@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: <?php $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]); } ?> --was-- 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]); } http://php.net/manual/en/function.array-search.php

« previous php.notes (#80020) next »