Add Array function to return only array entries based on matching key

A simple key based array filter
This commit is contained in:
Clemens Schwaighofer
2024-12-09 19:01:35 +09:00
parent a56cbd8e97
commit 65715ea9c3
3 changed files with 122 additions and 0 deletions

View File

@@ -525,6 +525,30 @@ class ArrayHandler
{
return array_diff($array, $remove);
}
/**
* From the array with key -> anything values return only the matching entries from key list
* key list is a list[string]
* if key list is empty, return array as is
*
* @param array<string,mixed> $array
* @param array<string> $key_list
* @return array<string,mixed>
*/
public static function arrayReturnMatchingKeyOnly(
array $array,
array $key_list
): array {
// on empty return as is
if (empty($key_list)) {
return $array;
}
return array_filter(
$array,
fn($key) => in_array($key, $key_list),
ARRAY_FILTER_USE_KEY
);
}
}
// __END__