Page 1 of 1

array filtering

Posted: Mon Oct 30, 2006 7:03 am
by sh33p1985
i have two arrays, one large, one small of 4 digit numbers

first array is numbered 0000-9999
second array contains unique entries of any of these numbers for example {0001, 1138, 2288, 4582}

im trying to filter these entries from the first array using the array_filter function
originally i used nested loops which was resulting in far too much processing for something that surely must be able to be done much more easily.

i did a simple callback function to make sure that the array filtering works, and does (see below) but id like to pass the second array to the function so it knows which entries to omit rather than hardcoding them.

Code: Select all

function omit($var){
if($var != "0000"){
return true;
}
else{
return false;
}	
}
print_r(array_filter($productNumbers, "omit"));

Posted: Mon Oct 30, 2006 7:07 am
by aaronhall
Are you trying to cycle through the first array to fetch only those numbers in the second array?

Posted: Mon Oct 30, 2006 7:09 am
by sh33p1985
more or less, im trying to output the 1st array, but omitting the numbers in the 2nd array.

Posted: Mon Oct 30, 2006 7:14 am
by aaronhall
As you're looping through the first, use in_array() to check that the current array value doesn't match any in the second array. If it does, skip the current loop.

Code: Select all

<?php
foreach($firstArray as $key => $value)
{
	if(!in_array($value, $secondArray)) {
		// continue processing this array entry
	} else {
		// this $value is in the second array... do nothing
	}
}
?>