Array search - Part 2

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
spacebiscuit
Forum Contributor
Posts: 390
Joined: Mon Mar 07, 2005 3:20 pm

Array search - Part 2

Post 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.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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);
}
spacebiscuit
Forum Contributor
Posts: 390
Joined: Mon Mar 07, 2005 3:20 pm

Post by spacebiscuit »

Many thanks, that works great now!

I misunderstood the function.

Thanks,

Rob.
Post Reply