Page 1 of 1

Array search - Part 2

Posted: Wed Aug 17, 2005 8:26 am
by spacebiscuit
Hi,

I have found some odd behavious with the array_serach fnction.

Look at this piece of code:

Code: Select all

$list=file("email_list.txt");
   
$list=array_map("trim",$list);

foreach($list as $val){
	echo "-$val-";
                      }
Output is as to be expected:

-1--2--3-

ie. the file is 3 lins long with the number 1,2,3 on each line. I am then searching the array for a match as follows:

Code: Select all

if (array_search('1', $list)) {
	echo"Value exists in the array!";
                                         }
Now the strange behaviour I have noticed is that array_search does not seem to look in or compare index 0 of the array. I have tested this, and which ever value is in index 0 - does not evalute to true when call the function.

Am I going mad?

Rob.

Posted: Wed Aug 17, 2005 8:36 am
by feyd
it's working correctly.. you're not looking at the return right.
Searches haystack for needle and returns the key if it is found in the array, FALSE otherwise.

Note: If needle is a string, the comparison is done in a case-sensitive manner.

Note: Prior to PHP 4.2.0, array_search() returns NULL on failure instead of FALSE.

Code: Select all

if(false !== ($index = array_search('1',$list)))
{
  echo "found it at index ".var_export($index,true);
}
else
{
  echo "did not find it: ".var_export($index,true);
}

Posted: Wed Aug 17, 2005 10:14 am
by spacebiscuit
Many thanks, that works great now!

I misunderstood the function.

Thanks,

Rob.