Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: preserving desired value in array

Tags:

arrays

php

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.

like image 641
user1899415 Avatar asked Jan 21 '26 10:01

user1899415


2 Answers

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);
like image 108
Ja͢ck Avatar answered Jan 24 '26 04:01

Ja͢ck


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

like image 20
Mark Miller Avatar answered Jan 24 '26 04:01

Mark Miller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!