Working with arrays often requires selecting or excluding a subset of keys. Many frameworks provide helper functions like array_only_keys() and array_except_keys() because developers repeatedly re‑implement this logic. This RFC proposes adding native PHP functions for these common operations.
Add two new functions to the PHP core:
The usage of the methods to handle the keys will look like:
<?php $data = [ 'id' => 1, 'name' => 'Name here', 'email' => 'name@test.com', ]; array_only_keys($data, ['id', 'email']); // Output // ['id' => 1, 'email' => 'name@test.com'] array_except_keys($data, ['email']); // Output // ['id' => 1, 'name' => 'Ali'] ?>
Here is a simple example of an array_only_keys() and array_except_keys implementation using existing PHP functions:
<?php function array_only_keys(array $input, array $keys): array { return array_intersect_key($input, array_flip($keys)); } function array_except_keys(array $array, array $keys) { return array_diff_key($array, array_flip($keys)); }
This works, but array_flip($keys) creates an extra temporary hash table.
So peak memory becomes: input + keys + flipped array + result.
In a native C implementation, we can iterate over $keys and copy values directly into the result without creating that temporary array.
That means fewer allocations and lower peak memory usage, especially with large key sets or inside loops.
See the implementation in Laravel: https://github.com/laravel/framework/blob/12.x/src/Illuminate/Collections/Arr.php#L724-L727
Laravel Arr::except implementation: https://github.com/laravel/framework/blob/12.x/src/Illuminate/Collections/Arr.php#L231-L236
<?php array_only_keys([], ['a']); // [] array_except_keys([], ['a']); // [] array_only_keys(['a'=>1], []); // [] array_except_keys(['a'=>1], []); // ['a'=>1] ?>
<?php array_only_keys(['a'=>1], ['b']); // [] array_except_keys(['a'=>1], ['b']); // ['a'=>1] ?>
<?php $a = [10, 20, 30, 40]; array_only_keys($a, [1, 3]); // [1 => 20, 3 => 40] array_except_keys($a, [0, 2]); // [1 => 20, 3 => 40] ?>
None
PHP 8.6
These two new functions are added to ext-standard, where array_only_keys() and array_except_keys() and array_only_keys() and array_except_keys() also live.
Primary Vote requiring a 2/3 majority to accept the RFC:
None
Current discussion: https://externals.io/message/130102
None
1.0: Initial version under discussion
1.1 Changed function names array_only() and array_except()
1.2 Laravel's link added