I have an array like this:
array(\"a\" => 2, \"b\" => 4, \"c\" => 2, \"d\" => 5, \"e\" => 6, \"f\" => 2)
Now I want to fi
You can iterate on the copies of the keys to be able to use unset()
in the loop:
foreach (array_keys($array) as $key) {
if ($array[$key] != 2) {
unset($array[$key]);
}
}
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):
$keys = array();
foreach ($array as $key => $value) {
if ($value == 2) {
$keys[] = $key;
}
}