How do I specify the array value to keep and throw everything else out?
$want_to_keep = 32
Array
(
[1015] => 78
[2316] => 78
[5374] => 32
[8913] => 78
[1397] => 32
)
I only want items with '32' values, so output:
Array
(
[5374] => 32
[1397] => 32
)
I looked at array_filter and array_intersect, both of which doesn't suit this need.
To replace the array with a filtered one:
$arr = array_filter($arr, function($value) use ($want_to_keep) {
return $value === $want_to_keep;
});
A stranger way:
$arr = array_fill_keys(array_keys($arr, $want_to_keep, true), $want_to_keep);
array_intersect() does exactly this.
Simply:
$want_to_keep = array(32);
$arr = Array
(
1015 => 78,
2316 => 78,
5374 => 32,
8913 => 78,
1397 => 32
);
print_r(array_intersect($arr, $want_to_keep));
Output:
Array
(
[5374] => 32
[1397] => 32
)
SEE DEMO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With