I’d like to know if there is any native way to extract a set of values and their keys from a large array using a smaller array of keynames.
compact() does this on separate variables but not on arrays:
$foo='foo';
$bar='bar';
print_r(compact('foo','bar'));
// or
print_r(compact(array('foo','bar'));
// Prints:
// Array(
// [0] => foo,
// [1] => bar
// )
So far I’ve always used foreach loops, but I started to wonder if a simpler method exists. I’ve gone through the PHP documentation’s Array functions section but still felt that I’d try asking in case I missed something.
To summarise what turned out more lengthy than I anticipated, the functions of interest to you are likely
array_flip()andarray_intersect_key().I hope I correctly understood what you wanted. You want to an array of variable names, where the variables themselves contain array keys, and you want to search a larger array for these keys?
Does this do what you want? I haven’t benchmarked it against a foreach, it’s quite possibly slower.
Output:
Edit:
From Gordons comment, if the use of
compactto use variable names as keys is irrelevant, you can substitute in the following code.You can further reduce the code by defining your array of keys slightly differently, and eliminating the need for
array_flip().