note 63338 added to function.array-search

From: Date: Mon, 20 Mar 2006 13:54:15 +0000
Subject: note 63338 added to function.array-search
Groups: php.notes 
Request: Send a blank email to php-notes+get-106105@lists.php.net to get a copy of this message
To expand on previous comments, here are some examples of where using array_search within an IF statement can go wrong when you want to use the array key thats returned. Take the following two arrays you wish to search: <?php $fruit_array = array("apple", "pear", "orange"); $fruit_array = array("a" => "apple", "b" => "pear", "c" => "orange"); if ($i = array_search("apple", $fruit_array)) //PROBLEM: the first array returns a key of 0 and IF treats it as FALSE if (is_numeric($i = array_search("apple", $fruit_array))) //PROBLEM: works on numeric keys of the first array but fails on the second if ($i = is_numeric(array_search("apple", $fruit_array))) //PROBLEM: using the above in the wrong order causes $i to always equal 1 if ($i = array_search("apple", $fruit_array) !== FALSE) //PROBLEM: explicit with no extra brackets causes $i to always equal 1 if (($i = array_search("apple", $fruit_array)) !== FALSE) //YES: works on both arrays returning their keys ?> ---- Server IP: 85.116.0.130 Probable Submitter: 82.44.160.226 ---- X-Spam-Status: No, hits=3.1 required=5.0 tests=DATE_MISSING,FROM_NO_LOWER autolearn=no version=2.64 ---- Manual Page -- http://www.php.net/manual/en/function.array-search.php Edit -- http://master.php.net/note/edit/63338 Del: integrated -- http://master.php.net/note/delete/63338/integrated Del: useless -- http://master.php.net/note/delete/63338/useless Del: bad code -- http://master.php.net/note/delete/63338/bad+code Del: spam -- http://master.php.net/note/delete/63338/spam Del: non-english -- http://master.php.net/note/delete/63338/non-english Del: in docs -- http://master.php.net/note/delete/63338/in+docs Del: other reasons-- http://master.php.net/note/delete/63338 Reject -- http://master.php.net/note/reject/63338 Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#106105) next »