Marco,

>  1. could you also provide the code for the benchmarks? I'd gladly measure
> them with an accurate tool
>

Yeah that would be great!  Here's the benchmark I was using:
https://gist.github.com/colinodell/872c1f0c92351af687347c0c8be4f253


>  2. do we really need another array function that is basically an
> `array_combine(array_map($someFunc, array_keys($arr)), $arr)`?
>

While array_combine() technically works, the callback does not have access
to both the key AND value.  Anyone needing access to both must currently
resort to using a foreach loop (unless there's some other clever
combination of functions that I'm missing).

We already have array_change_key_case().  IMO that function is way too
specific and not applicable in 99% of situations where you need to re-key
an array.  This is why I'm proposing a general purpose function custom
tailored to rekeying an array.

I'll touch on some other advantages further down this message.

 3. and... do we really want another function that accepts arrays and not
> generic Traversable (and therefore also generators)?
>

Do the other array functions support this?  If not then I'd argue that
adding Traversable support to array functions should be part of a broader
RFC which adds this support to all applicable functions at once.

In the mean time, you could certainly use iterator_to_array with this
proposed function:

    $b = array_change_keys(iterator_to_array($a), $callback);

Doing this with array_combine() would require an intermediate variable to
prevent a "Fatal error: Uncaught Exception: Cannot traverse an already
closed generator":

    $b = iterator_to_array($a);
    $a = array_combine(array_map($callback, array_keys($b)), $b);

Even if all array functions did support generators you'd still need this
intermediate variable to prevent the double traversal - array_change_keys()
would not have this problem.


>  4. what is the real-world benefit over just
> `array_combine(array_map($someFunc, array_keys($arr)), $arr)`, except for
> the two additional function calls here?
>

There are several IMO:

1. Callback has access to both the original key AND the original value.
The array_combine() approach can only access one or the other.
2. Better performance (hoping you can confirm this).
3. Purpose of the array_*() function is immediately obvious.
4. No need for intermediate variable when working with iterators means
function composition is possible.

Thanks for the feedback!

Colin

Reply via email to