only fetch specific array keys php 1

only fetch specific array keys php

$array = [
    'a' => 4,
    's' => 5,
    'd' => 6,
];
$onlyKeys = ['s','d'];

$filteredArray = array_filter($array, function($v) use ($onlyKeys) {
    return in_array($v, $onlyKeys);
}, ARRAY_FILTER_USE_KEY);

prinr_r($filteredArray); //  ['s' => 5, 'd' => 6]

Here is what the above code is Doing:
1. We have an array of key-value pairs.
2. We have an array of keys that we want to filter by.
3. We use array_filter to filter the array.
4. We use the ARRAY_FILTER_USE_KEY flag to tell array_filter to use the keys of the array as the values to filter by.
5. We use a closure to check if the key is in the array of keys we want to filter by.
6. We return the filtered array.

Similar Posts