I have an array like this:
array("a" => 2, "b" => 4, "c" => 2, "d" => 5, "e" => 6, "f" => 2)
Now I want to filter that array by some condition and only keep the elements where the value is equal to 2 and delete all elements where the value is NOT 2.
So my expected result array would be:
array("a" => 2, "c" => 2, "f" => 2)
Note: I want to keep the keys from the original array.
How can I do that with PHP? Any built-in functions?
I might do something like:
This should work, but I'm not sure how efficient it is as you probably end up copying a lot of data.
I think the snappiest, readable built-in function is: array_intersect()
Code: (Demo)
Output:
Just make sure you declare the 2nd parameter as an array because that is the value type expected.
Now there is nothing wrong with writing out a foreach loop, or using
array_filter()
, they just have a more verbose syntax.array_intersect()
is also very easy to extend (include additional "qualifying" values) by adding more values to the 2nd parameter array.You can iterate on the copies of the keys to be able to use
unset()
in the loop:The advantage of this method is memory efficiency if your array contains big values - they are not duplicated.
EDIT I just noticed, that you actually only need the keys that have a value of 2 (you already know the value):
You somehow have to loop through your array and filter each element by your condition. This can be done with various methods.
Loops
while
/for
/foreach
methodLoop through your array with any loop you want, may it be
while
,for
orforeach
. Then simply check for your condition and eitherunset()
the elements if they don't meet your condition or write the elements, which meet the condition, into a new array.Looping
Condition
Just place your condition into the loop where the comment
//condition
is. The condition can just check for whatever you want and then you can eitherunset()
the elements which don't meet your condition, and reindex the array witharray_values()
if you want, or write the elements in a new array which meet the condition.array_filter()
methodAnother method is to use the
array_filter()
built-in function. It generally works pretty much the same as the method with a simple loop.You just need to return
TRUE
if you want to keep the element in the array andFALSE
if you want to drop the element out of the result array.preg_grep()
methodpreg_grep()
is similar toarray_filter()
just that it only uses regular expression to filter the array. So you might not be able to do everything with it, since you can only use a regular expression as filter and you can only filter by values or with some more code by keys.Also note that you can pass the flag
PREG_GREP_INVERT
as third parameter to invert the results.Common conditions
There are many common conditions used to filter an array of which all can be applied to the value and or key of the array. I will just list a few of them here: