1

I have the following array. How would I delete (unset) all elements in it for the following two scenarios?

  1. Delete all elements where prop is equal to "a". Should delete element 0 and 2.
  2. Delete all elements where prop is in array("a","d"). Should delete elements 0, 2, and 3.

I can obviously iterate over the array, and check if there is a match, but I expect there is a more efficient way to do so.

Array
(
    [0] => obj Object
        (
            [prop] => a
        )

    [1] => obj Object
        (
            [prop] => b
        )

    [2] => obj Object
        (
            [prop] => a
        )

    [3] => obj Object
        (
            [prop] => d
        )

)

2 Answers 2

3

array_filter (PHP documentation here) is probably the best solution for that.

It will of course iterate over your array though, but it separates the iteration logic from the filtering logic, making it easier to maintain your code.

function filter_on_prop($val) {
  $arr = ['a', 'b'];
  return (!in_array($val->prop, $arr));
}

$array = array_filter ($array, 'filter_on_prop');

With an anonymous function :

$array = array_filter ($array, function ($val) use ($filter) {
  return (!in_array($val->prop, $filter));
});

$filter being your array previously selected / filled to check whatever you want.

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

4 Comments

Thanks Clement. Nice solution. I suppose this could also be done using an anonymous function?
I will experiment and post how it could be done with an anonymous function. Without (or with) an anonymous, is it possible to remove $arr = ['a', 'b']; from inside the function so it is more user selectable? For instance, I could run it for ['a', 'b'] as well as ['a']
@user1032531 Yes, updated my answer according to what you want. It just depends what you want and if you're going to use your function a lot. I tend to use a callback and to include arrays (or filters) in my functions as I think it makes it easier to know WHERE I've to edit some code to change the behavior.
Perfect! I never used use before. Only thing I needed to change is function () to function ($val).
0

You can use array_filter for this:

$allowedProps = array('a','d');

$myfilter = function($val) use ($allowedProps)
{
    return !in_array($val->prop, $allowedProps);
}

$myfilteredArray = array_filter($array, $myFilter);

1 Comment

Looks like Clément was faster :p

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.