开发者

php elegance keys unsetting

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.


You can do that with single call to unset as:

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


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');


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.


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.


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');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜