Is there a shorthand for the following code:
$result = array_combine(
array_map(fn($elem) => "key_$elem", $array),
array_map(fn($elem) => "value_$elem", $array)
);
I do not like the idea (from readability point of view) of having to use array map twice on the same array and then combining the intermediate results.
Update 2024-03-08:
To my surprise,
substr_replace()calls inside ofarray_combine()(solitary demo) outperformsforeach()frequently enough to consider it "the best" in my eyes. (Demo)Output for 8.3.4 (hand sorted ASC)
Original answer:
I find this contrived task to be rather unrealistic (unfathomable as a real word use case). The preference of code styling is going to come down to personal preference.
If we are going to consider options from an academic vector, then we should not only compare code brevity, but also time complexity, directness, minimizing function calls, and perhaps even memory.
TL;DR:
Classic language construct iteration (like
foreach()) will consistently outperform functional iterators. Using generators means a trade off of performance for memory savings.All other functional iterators are near enough in there execution time that you probably shouldn't waste development time thinking about which one is fastest.
Of all of the approaches that I tested, only
array_reduce()encountered a catastrophic memory problem. After researching, I found that using an ArrayObject will overcome the under-the-hood memory challenges (for when you cannot simply increase the memory allowance).Now I will list the different approaches pulled from this earlier answer to a VERY similar question which I tweaked and extended with a few more approaches.
Generator with
foreach()An ordinary
foreach()loop:array_combine()with two nestedarray_map()calls:Flattening an 2d array:
Convert a 2d array into an associative with
array_column():array_walk()with reference array:array_reduce()built to handle large payloads:My testing script: (Demo)
Results for PHP8.3.4 (sorted by speed):
Results for PHP8.3.3 (sorted by speed):
If I was to need such a process to be executed in a professional application, I'd probably use @User863's snippet -- it is clean, direct, functional-style, and doesn't bother making more than one iteration.
Note that I was not able to use the union operator
+in myarray_reduce()script because it doesn't work with ArrayObject type data.If I had performance concerns, I'd use a foreach.
If I had memory concerns, I'd use a generator.