RE: [PHP] how to make array_search start from 0?

From: Date: Thu, 25 Apr 2002 17:34:52 +0000
Subject: RE: [PHP] how to make array_search start from 0?
Groups: php.general 
Request: Send a blank email to php-general+get-94594@lists.php.net to get a copy of this message
> -----Original Message----- > From: andy [mailto:news.letters@gmx.de] > Sent: 25 April 2002 17:30 > > I am passing an array through the URL with a ',' inbetween: > var=php,mysql,super > Parsing is done with: explode (',',$var). This gives me an > array starting > with 0 > > Later on I have to search for lets say php with array_search. > > Unfortunatelly array_search requires an array starting with > 1. No, it doesn't. The key here is in the big warning at the bottom of the manual entry for array_search (http://www.php.net/array_search), which says: ============================== Warning This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function. ============================== So, if what you search for is at key 0, array_search will return zero, which evaluates to FALSE if you do an == (or !=) test on it. Unfortunately, the return value for "not found" changed for version 4.2.0 -- it used to be NULL, but is now FALSE, so you will have to write your test accordingly. Something like this should do it: Versions prior to 4.2.0: $i = array_search('abc', $arr); if (!isnull($i)): // 'abc' was found endif; 4.2.0 and up: $i = array_search('abc', $arr); if ($i!==FALSE): // 'abc' was found endif; Cheers! Mike --------------------------------------------------------------------- Mike Ford, Electronic Information Services Adviser, Learning Support Services, Learning & Information Services, JG125, James Graham Building, Leeds Metropolitan University, Beckett Park, LEEDS, LS6 3QS, United Kingdom Email: m.ford@lmu.ac.uk Tel: +44 113 283 2600 extn 4730 Fax: +44 113 283 3211

« previous php.general (#94594) next »