[SOLVED] Array Oddities

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
NoReason
Forum Commoner
Posts: 51
Joined: Tue Sep 10, 2002 6:19 pm

[SOLVED] Array Oddities

Post by NoReason »

Ok, im doing somthing fairly retuine here but for some reason, when search my array using my own function or the built in function... It never returns true if the element I am search for is sitting in Index zero.

Code: Select all

function searchArray($needle,$haystack)
{
	$retKey = false;
		
		while (list($key, $val) = each($haystack))
		{	
			if( $val == $needle )
				$retKey = $key;

			echo $val.':'.$needle.'<br>';
		&#125;
		
	return $retKey;
&#125;


$blah = array(1,2,3,4,5,6,7,8,9,0);

if($key = searchArray(1,$blah))
	echo $key.'<br>';
else
	echo 'nomatch';


The echo shows this.
1:1
2:1
3:1
4:1
5:1
6:1
7:1
8:1
9:1
0:1
nomatch

However If I use the same code but search for a value not in index zero;

Code: Select all

if($key = searchArray(2,$blah))
	echo $key.'<br>';
else
	echo 'nomatch';


I get;
1:2
2:2
3:2
4:2
5:2
6:2
7:2
8:2
9:2
0:2
1 <-- being the index the function found the element

Any ideas as to what the hell is going on?
microthick
Forum Regular
Posts: 543
Joined: Wed Sep 24, 2003 2:15 pm
Location: Vancouver, BC

Post by microthick »

This is because 0 is the same as false. So, if $key is 0, it assumes you meant false and goes to your else statement.
NoReason
Forum Commoner
Posts: 51
Joined: Tue Sep 10, 2002 6:19 pm

Post by NoReason »

omg ... my brain hurt on that one.. thanks
Post Reply