0

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?

2
  • So what would be the expected output? If you want to preserve the keys?! Commented Mar 26, 2015 at 13:20
  • The above foreach works perfectly fine and I've shown the expected output with preserved keys. I'm wondering if there is build-in function that does the same. array_filter does it but it resets the keys (it generates new array with the non-filtered items). Commented Mar 26, 2015 at 13:21

3 Answers 3

7

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
)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, does exactly what I want.
0
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

3 Comments

This is just a complete copy of this answer: stackoverflow.com/a/29279629/3933332
yes but provide explanation what actually happen using those functions
Well, I think it's pretty clear, but you can edit other's answers to add descriptions.
-3

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

3 Comments

Haven't you heard @PaulCrovella. Laravel is great and does all the things!
@PaulCrovella I meant the function was more based on the one Laravel defined for this task rather than, “Laravel defines functions, so therefore that’s the way to go!”
@PeeHaa See previous comment.

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.