[SOLVED] Drop empty keys (arrays)

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
mevets
Forum Newbie
Posts: 23
Joined: Fri Sep 15, 2006 10:06 am

[SOLVED] Drop empty keys (arrays)

Post by mevets »

I have an array of users. I have another array that contains users from the first array that I want deleted. This how I've attempted it:

Code: Select all

$masterlist = array(0 => "user0", 1 => "user1", 2 => "user2", 3 => "user3");
$dellist = array(0 => "user1", 1 => "user2");
foreach ($dellist as $needle) {
  if (array_search($needle, $masterlist));
    $masterlist[array_search($needle, $masterlist)] = null; 
}
print_r($masterlist);
I'm left with an array with holes in it. Is there a way to now collapse the array where there are null values? Should I be taking another approach all together?
Last edited by mevets on Fri Jun 29, 2007 11:16 pm, edited 1 time in total.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

array_filter() is the answer to your specific question, but array_diff() may be of interest.
mevets
Forum Newbie
Posts: 23
Joined: Fri Sep 15, 2006 10:06 am

Post by mevets »

thanks, solution

Code: Select all

$masterlist = array(0 => "user0", 1 => "user1", 2 => "user2", 3 => "user3");
$dellist = array(0 => "user1", 1 => "user2");
$diff = array_diff($masterlist, $dellist);
print_r($diff);
Post Reply