Hi Tim,

Thanks for the explanation.

In this example,

$dataWithOnlyIdAndEmail = \array_intersect_key($data, ['id' => 0, 'email'
=> 1]);


the second argument is an associative array.

But in my *array_only(array $input, array $keys) *function, *$keys* is
a *numeric
array.* Working with a *numeric array* may be slightly faster than building
an associative array first.


Just wanted to clarify that point.


Best regards,

Muhammed Arshid KV

On Sun, 1 Mar 2026, 7:40 pm Tim Düsterhus, <[email protected]> wrote:

> Hi
>
> Am 2026-02-22 19:58, schrieb Muhammed Arshid KV:
> > Here is a simple example of an `array_only()` implementation using
> > existing
> > PHP functions:
> >
> > ```php
> > function array_only(array $input, array $keys): array {
> >     return array_intersect_key($input, array_flip($keys));
> > }
> > ```
> >
> > This works, but `array_flip($keys)` creates an extra temporary hash
> > table.
> > So peak memory becomes: input + keys + flipped array + result.
>
> That 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_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.
>

Reply via email to