-2

Given the following array:

$data = [
    'a' => 1,
    'b' => 2,
    'c' => 3
];

Is there a PHP function that, called this way:

x($data, ['a', 'c']);

Would return this result:

[
    'a' => 1,
    'c' => 3
]

Please note that I know how to write the code to generate the expected result, so please only answer if there is a native PHP function to do that, or alternatively to mention that there isn't, if you know this for a fact.

BenMorel
  • 34,448
  • 50
  • 182
  • 322

1 Answers1

3

There's no built-in function that does the exact same thing, but you can easily combine two of them to achieve what you want:

$keys = ['a', 'c'];
$result = array_intersect_key($data, array_flip($keys));

array_flip() flips the values and keys of a given array — this is done to transform your search values into keys of an array. array_intersect_key() compares the keys of the two arrays and returns the matches.

Demo

Amal Murali
  • 75,622
  • 18
  • 128
  • 150