Page 1 of 1

[SOLVED] Array Oddities

Posted: Wed Nov 26, 2003 2:22 pm
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?

Posted: Wed Nov 26, 2003 2:52 pm
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.

Posted: Wed Nov 26, 2003 3:19 pm
by NoReason
omg ... my brain hurt on that one.. thanks