8

I need to remove from an array some keys.

$array = array('a' => 'a', 'b' => 'b', 'c' => 'c');
unset($array['a']);
unset($array['b']);

How can I do this more elegance? Maybe there is a function like this array_keys_unset('a', 'b')?
I don't need array_values or foreach. I only want to know is it possible.
Thank you in advance. Sorry for my english and childlike question.

Alex Pliutau
  • 21,392
  • 27
  • 113
  • 143

5 Answers5

15

You can do that with single call to unset as:

unset($array['a'],$array['b']);
codaddict
  • 445,704
  • 82
  • 492
  • 529
5

unset() is as simple as it gets, but as another solution how about this?

$keys_to_remove = array_flip(array('a', 'b'));
$array = array_diff_key($array, $keys_to_remove);

Put into a function:

function array_unset_keys(array $input, $keys) {
    if (!is_array($keys))
        $keys = array($keys => 0);
    else
        $keys = array_flip($keys);

    return array_diff_key($input, $keys);
}

$array = array_unset_keys($array, array('a', 'b'));

Or you could even make it unset()-like by passing it a variable number of arguments, like this:

function array_unset_keys(array $input) {
    if (func_num_args() == 1)
        return $input;

    $keys = array_flip(array_slice(func_get_args(), 1));

    return array_diff_key($input, $keys);
}

$array = array_unset_keys($array, 'a', 'b');
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
3

Personally, I would just do this if I had a long / arbitrary list of keys to set:

foreach (array('a', 'b') as $key) unset($array[$key]);

You could use a combination of array functions like array_diff_key(), but I think the above is the easiest to remember.

Matthew
  • 47,584
  • 11
  • 86
  • 98
3

What's wrong with unset()?

Note that you can do unset($array['a'], $array['b']);

You could also write a function like the one you suggested, but I'd use an array instead of variable parameters.

aib
  • 45,516
  • 10
  • 73
  • 79
3

No, there is no predefined function like array_keys_unset.

You could either pass unset multiple variables:

unset($array['a'], $array['b']);

Or you write such a array_keys_unset yourself:

function array_keys_unset(array &$arr) {
    foreach (array_slice(func_get_args(), 1) as $key) {
        unset($arr[$key]);
    }
}

The call of that function would then be similar to yours:

array_keys_unset($array, 'a', 'b');
Gumbo
  • 643,351
  • 109
  • 780
  • 844
  • +1 Cleanest of all solutions though I hate PHP's array_xxx method nomenclature. Let's call it something else ... e.g. `strip_keys`. – aefxx Dec 10 '10 at 15:04