-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'"?

1
  • I make a function removeByWhere in my answer, you can try to use it. Commented Nov 21, 2013 at 1:43

3 Answers 3

1

Use array_filter with a callback with the conditions you want

Sign up to request clarification or add additional context in comments.

1 Comment

This is the short version of what I consider the right answer, thanks Matt.
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);
    }
}

3 Comments

I don't think the OP wants to remove the first name, but the whole user.
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?
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.
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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.