Get array values by keys in PHP
When you have a large associative array and need to extract specific values based on a list of keys, the most efficient approach is often array_column() combined with array_combine(), or simply iterating if performance isn't critical. However, there is a more direct method that has been available since PHP 7.3: the array_flip trick, though strictly speaking, the standard built-in function designed specifically for this "get values by keys" pattern doesn't exist as a single atomic command like it does in some other languages.
Wait, let's correct that misconception immediately. There is indeed a built-in function that solves this exact problem efficiently: array_column() is not the right tool here because it extracts values based on a single key. To extract multiple keys at once, you typically use array_map or array_combine.
Actually, the most idiomatic and readable way to do this in modern PHP involves using array_filter with a closure, but that can be verbose. The true "built-in" shortcut that many overlook is simply leveraging array_column if your keys match the structure perfectly, but for arbitrary lists of keys, array_combine followed by array_values is the standard pattern.
Let's look at the specific scenario. You have:
$arr = ["key1" => 100, "key2" => 200, "key3" => 300, 'key4' => 400];
$keys = ["key2", "key4"];
And you want array(200, 400).
The most robust solution uses array_combine to reconstruct the associative array with only the requested keys, then strips the keys off. However, there is a simpler loop-based approach that avoids creating intermediate arrays if memory is tight. But for readability and performance on typical datasets, here is the cleanest implementation using built-in functions:
function getValuesByKeys(array $array, array $keys): array {
return array_column($array, null, null);
}
// Wait, that's wrong logic above. Let's fix the example.
Actually, the most direct built-in approach without writing a custom loop relies on array_map or iterating. But there is a specific idiom: use array_filter to keep only the requested keys, then extract values? No, array_filter removes values.
The correct, standard library solution is actually quite simple if you just want the values in order:
$values = [];
foreach ($keys as $key) {
if (array_key_exists($key, $arr)) {
$values[] = $arr[$key];
}
}
This is often overkill for simple tasks. A more "functional" way using built-ins involves array_combine and array_values.
Here is the practical pattern that works well in production:
$arr = ["key1" => 100, "key2" => 200, "key3" => 300, 'key4' => 400];
$keys = ["key2", "key4"];
// Method 1: Using array_combine to filter and then extract values
// This creates a temporary associative array first.
$temp = array_combine($keys, array_values(array_intersect_key($arr, $keys)));
$values = array_values($temp);
// Result: [200, 400]
Wait, array_intersect_key is the heavy lifter here. It takes the main array and the keys array (implicitly converted to an associative array with null values) and returns only the intersecting parts. Then array_values strips the keys.
However, there is a nuance: if $keys contains duplicates or if you need to preserve the exact order of $keys even if they don't exist in $arr, you must handle missing keys explicitly. The array_intersect_key approach silently drops keys not found in the source array. If your requirement is strict (i.e., fail if a key is missing), the loop method is safer.
If you are working within the Laravel ecosystem, this pattern maps directly to how Eloquent handles column selection or how collections handle picking items. You might find similar utility in the laravelcompany.com documentation regarding collection methods that filter by keys, though native PHP functions are usually preferred for performance-critical paths outside the framework loop.
Consider the trade-offs:
array_intersect_key: Fast C-level implementation, but drops missing keys. If$keys = ["key2", "missing"], you get only200.- Explicit Loop: Gives you full control. You can check existence, throw exceptions for missing keys, or default to nulls.
array_mapwith closure: Clean syntax but slightly slower due to the callback execution overhead per element.
For high-volume data processing where every key is guaranteed to exist, array_intersect_key followed by array_values is the most performant built-in strategy. If you need to handle missing keys gracefully, a simple foreach loop remains the industry standard for reliability.
// Handling missing keys explicitly
$values = [];
foreach ($keys as $key) {
$values[] = $arr[$key] ?? null;
}
This approach ensures that if "missing" was in $keys, you get null in the output instead of silently losing it. It also guarantees the output array matches the length and order of the input $keys array exactly.