ddinchev
ddinchev

Reputation: 34673

Remove items with certain keys from array

I have an array that looks like this:

$arr = [
    0 => "A",
    1 => "B",
    2 => "C",
    3 => "D",
    4 => "E",
];

And I want to delete few of the items, I have array of their keys:

$delKeys = [0,2,3];

The following procedure shows what I want to achieve:

foreach ($delKeys as $dk) {
    unset($arr[$dk]);
}

I'm left with:

array(
    [1] => "B",
    [4] => "E",
)

Is there a build in method that does the above 3-liner, like array_filter, but preserving the keys of the original array?

Upvotes: 0

Views: 138

Answers (3)

Navneet Garg
Navneet Garg

Reputation: 1374

array_diff_key($arr, array_flip($delKeys))

array_flip function will flip values in to keys and than array_diff_key find the difference between both the arrays

Upvotes: 0

Martin Bean
Martin Bean

Reputation: 39389

You could always define your own function for this task:

/**
 * Remove the specified keys from a given array.
 *
 * @param  array $array
 * @param  array $keys
 * @return array
 */
function array_forget(array $array, array $keys)
{
    foreach ($keys as $key)
    {
        unset($array[$key]);
    }

    return $array;
}

Usage:

$arr = array_forget($arr, [0,2,3]);

Upvotes: -3

user3942918
user3942918

Reputation: 26375

Two functions, but one line at least - array_diff_key() along with array_flip():

array_diff_key($arr, array_flip($delKeys))

Array
(
    [1] => B
    [4] => E
)

Upvotes: 7

Related Questions