skip to Main Content

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));

PHP Sandbox

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.

3

Answers


  1. Chosen as BEST ANSWER

    Thanks for the suggestions. However, I have reached a solution that I like more:

    $result = array_merge(...array_map(fn($elem) => ["key_$elem" => "value_$elem"], $array));
    

    PHP Sandbox


  2. You can use array_reduce

    https://www.php.net/manual/en/function.array-reduce.php

    $result = array_reduce($array, fn ($carry, $item) => $carry + ["key_$item" => "value_$item"], []);
    

    PHP Sandbox

    Login or Signup to reply.
  3. I’d just define simple function, like that:

    function array2map($a) {
        $r = []; foreach ($a as $v) $r['key_'.$v] = 'value_'.$v; return $r;
    }
    
    $result = array2map($array);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search