Re: Question about array_search
| From: | John Holmes | Date: | Mon, 11 Oct 2004 17:11:57 +0000 |
| Subject: | Re: Question about array_search | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-199213@lists.php.net to get a copy of this message | ||
Greg Donald wrote:
On Mon, 11 Oct 2004 09:07:13 -0700, Brian Dunning <brian@briandunning.com> wrote:You don't need all that, as it's already been pointed out. $a = array_search('John',$names); if($a === FALSE) { echo 'John is not in the array'; } else { echo "John is at position $a in the array."; } -- ---John Holmes... Amazon Wishlist: www.amazon.com/o/registry/3BEXC84AB3A5E/ php|architect: The Magazine for PHP Professionals – www.phparch.comSay I'm trying to add a value to an array, only if it's not already in there somewhere; so I do an array_search to see. The problem is that if the item is at index 0 in the array, array_search gives the same answer as if it's not in there at all. How does one circumvent this potential pitfall?Do not use array_search() as a boolean test, it returns mixed results, it will cause issues withthe zero index as younoted. Instead use it to match an array key, then see if the key exists with isset() and compare it to the item you mean to add to the array.