Reputation: 26281
I have the following array. How would I delete (unset) all elements in it for the following two scenarios?
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
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
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