Jump to content

array search problem


doucettej3

Recommended Posts

Im having a problem with the output of my search..Itll say theres a match when there isnt. heres the code:

function search_array($passed_array, $search_num, $random_quantity)
{ 
$result = 0;
for($i = 0; $i <= $random_quantity; $i++)
{
if($search_num = $passed_array[$i])
{
$result = 1;
}	
if($result = 1)
{
echo"<br>There is a match";
return 0;
}
} 
if($result = 0)
{
echo "<br>No Matches Found";
}	
}

Link to comment
https://forums.phpfreaks.com/topic/132156-array-search-problem/
Share on other sites

thanks, I changed that problem now it just returns no matches found even if a match is there.

function search_array($passed_array, $search_num, $random_quantity)
{ 
$result = 0;
for($i = 0; $i <= $random_quantity; $i++)
{
if($search_num == $passed_array[$i])
{
$result = 1;
}	
if($result == 1)
{
echo"<br>There is a match";
return 0;
}
} 
if($result == 0)
{
echo "<br>No Matches Found";
}	
}

Link to comment
https://forums.phpfreaks.com/topic/132156-array-search-problem/#findComment-686841
Share on other sites

The logic seems right I would print out what is being passed to that function and verify the contents.

 

<?php
function search_array($passed_array, $search_num, $random_quantity)
{
   $result = 0;
   for($i = 0; $i <= $random_quantity; $i++) {
	if($search_num == $passed_array[$i]) {
		echo"<br>There is a match";
		return 0;
	}
   }
   
   if($result == 0) {
	echo "<br>No Matches Found";
   }   
}

?>

 

A revised version of your code, no need for that second if statement inside the for, since it returns 0 that ends the loop and exits the function. No other code will be executed.

Link to comment
https://forums.phpfreaks.com/topic/132156-array-search-problem/#findComment-686850
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.