user1032531
user1032531

Reputation: 26281

Delete array elements when property is of a given value

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
        )

)

Upvotes: 1

Views: 48

Answers (2)

Clément Malet
Clément Malet

Reputation: 5090

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.

Upvotes: 3

Pinoniq
Pinoniq

Reputation: 1385

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

Upvotes: 0

Related Questions