I have an array like this:
array(\"a\" => 2, \"b\" => 4, \"c\" => 2, \"d\" => 5, \"e\" => 6, \"f\" => 2)
Now I want to fi
I think the snappiest, readable built-in function is: array_intersect()
Code: (Demo)
$array = array("a" => 2, "b" => 4, "c" => 2, "d" => 5, "e" => 6, "f" => 2);
var_export(array_intersect($array, [2]));
Output:
array (
'a' => 2,
'c' => 2,
'f' => 2,
)
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.