array filtering

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
sh33p1985
Forum Commoner
Posts: 78
Joined: Thu Mar 11, 2004 9:22 am

array filtering

Post 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"));
User avatar
aaronhall
DevNet Resident
Posts: 1040
Joined: Tue Aug 13, 2002 5:10 pm
Location: Back in Phoenix, missing the microbrews
Contact:

Post by aaronhall »

Are you trying to cycle through the first array to fetch only those numbers in the second array?
sh33p1985
Forum Commoner
Posts: 78
Joined: Thu Mar 11, 2004 9:22 am

Post by sh33p1985 »

more or less, im trying to output the 1st array, but omitting the numbers in the 2nd array.
User avatar
aaronhall
DevNet Resident
Posts: 1040
Joined: Tue Aug 13, 2002 5:10 pm
Location: Back in Phoenix, missing the microbrews
Contact:

Post 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
	}
}
?>
Post Reply