Re: [RFC] array_only() and a rray_except() – Utility functions for array key f iltering
| From: | Tim Düsterhus | Date: | Sun, 01 Mar 2026 14:10:36 +0000 |
| Subject: | Re: [RFC] array_only() and a rray_except() – Utility functions for array key f iltering | ||
| References: | 1 2 3 4 5 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-130209@lists.php.net to get a copy of this message | ||
Hi
Am 2026-02-22 19:58, schrieb Muhammed Arshid KV:
Here is a simple example of anThat is true for this specific implementation of a “wrapper function”. It is not necessarily true for other implementations, e.g. simply using the functions directly instead of creating a wrapper for two method calls.array_only()implementation using existing PHP functions:function array_only(array $input, array $keys): array { return array_intersect_key($input, array_flip($keys)); }This works, butarray_flip($keys)creates an extra temporary hash table. So peak memory becomes: input + keys + flipped array + result.
array_flip() supports compile-time evaluation, so you can just write:
$dataWithOnlyIdAndEmail = \array_intersect_key($data, \array_flip(['id', 'email']));and OPcache will make sure to rewrite it to:
$dataWithOnlyIdAndEmail = \array_intersect_key($data, ['id' => 0, 'email' => 1]);avoiding the intermediate array. Best regards Tim Düsterhus PS: It appears that the RFC is not listed in the overview at https://wiki.php.net/rfc.