Jump to content

How Best To Search Array


johnsmith153

Recommended Posts

Array 1 holds about 1000 records, each with about 500 characters in each array

 

Array 2 holds about 10 records, each with about 20 characters each.

 

 

Array 2 holds a value that if contained in Array 1 - I need it removing

 

so if array 2 had 5 records that were contained in array 1, I would be left with 995 records in array 1

 

 

A possible way:

 

$array3=array();

 

foreach ($array1 as $value1)

{

 

$dontaddme=0;

 

foreach ($array2 as $value2)

{

 

 

if($value2 is contained in $value1 somewhere){$dontaddme=1;}

 

}

 

if($dontaddme!=1)

{

$array3[]=$value1;

}

 

}

 

 

I would then be left with 995 (or whatever) records in $array3

 

 

 

I need the best way to do it, plus if above is ok, how do I do where I search for a value inside an array.

Link to comment
https://forums.phpfreaks.com/topic/126383-how-best-to-search-array/
Share on other sites

Me I dunno if this would be easier but I would take my array  and run it through a while loop

breaking each record into a var during each loop through the while.. then pending on what your looking for is it specific string or word, letter, number?.. would while in the same loop have it search for what you want removed, remove it then finish the loop and reloop.. dunno if that makes sence, im tired, and burnt out.. sorry lol, im just kinda floating

Doesn't work Darkwater.

 

This works, but notice my str_replace line - it works great, but I am sure I am the only person to do this!

 

Anybody got a quicker way than mine?

 


$array1=array();
$array1[0]="jim smith";
$array1[1]="john brown";
$array1[2]="bob roberts";
$array1[3]="bob brown";

$array2=array();
$array2[0]="brown";
$array2[1]="roberts";
$array2[2]="brown";
$array2[3]="daniels";


echo "0: ".$array3[0]."<br>";
echo "1: ".$array3[1]."<br>";
echo "2: ".$array3[2]."<br><br><br>";

exit;


function remove_element($arr, $val){
foreach ($arr as $key => $value){

if (str_replace($val, "", $arr[$key])!=$arr[$key]){
unset($arr[$key]);
}
}
return $arr = array_values($arr);
}

foreach($array2 as $record)
{
$array1=remove_element($array1, $record);
}


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.