-1

Let's say you have a php array filled with dictionaries/associative arrays of first and last names, like so:

$userList = array(array('first'=>'Jim', 'last'=>'Kirk'), array('first'=>'George', 'last'=>'Bush'));
/*
$userList now looks like
{
    {
        first => Jim,
        last => Kirk
    },
    {
        first => George,
        last => Bush
    }
}
*/

How do I tell php to "Remove elements from $userList as $users where $user['first'] === 'George'"?

SG1
  • 2,871
  • 1
  • 29
  • 41

3 Answers3

1

foreach and use a reference & to be able to modify / unset that array element:

foreach($userList as &$user) {
    if($user['first'] == 'George') {
        unset($user);
    }
}
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
  • I don't think the OP wants to remove the first name, but the whole user. – Matt Nov 21 '13 at 01:48
  • Intriguing. So, you're just "unset"ing variables inside the array, without ever telling the array, and that works and doesn't cause a crash? – SG1 Nov 21 '13 at 02:42
  • This is very common and the reason they added the reference to the `foreach`. Just saw your answer (WOW), can't say that I would build a *function* to return a *closure* and run it through `array_filter`. Actually, I can say, I wouldn't. – AbraCadaver Nov 21 '13 at 03:26
1

Use array_filter with a callback with the conditions you want

Matt
  • 5,478
  • 9
  • 56
  • 95
0

Here's how I did it (based on "Charles"'s answer from This Question)...

First, I created a function-factory:

function createNotNamedFunction($first)
{
    return function($user) use($first) { 
        return $user['first'] !== $first;
    };
}

Then, I call it when I need to filter the array:

$first = 'George';
$notNamed = self::createNotNamedFunction($first);
$filteredUsers = array_filter($userList, $notNamed);

Short, simple to understand, extensible (the test can be arbitrarily complex since it's a first-class function), and doesn't involve loops.

This technique uses closures, array_filter, and only works in PHP 5.3 or greater, but it's what I would consider the canonical answer. It turns out that array_filter is "remove from array where" when you provide it with an arbitrary test.

Thanks to all world-class php wizards who contributed alternative patterns!

Community
  • 1
  • 1
SG1
  • 2,871
  • 1
  • 29
  • 41