How can I use array_map with keys and values, but return an array with the same indexes (not int)?

user2816456 picture user2816456 · Aug 26, 2014 · Viewed 45.3k times · Source

I have an array such as ['id' => 1, 'name' => 'Fred'].

I want to call array_map on this array and also use the key inside the function. However, when I make a return, my keys will become int.

Simple example :

$arr = array('id' => 1, 'name' => 'Fred');
$result = array_map(
    function ($value, $key) {
        return $value;
     },
     $arr,
     array_keys($arr)
);
var_dump($result);

Basically, I want $result to be identical to $arr in this case, but it turns my string keys into ints.

Answer

Jannie Theunissen picture Jannie Theunissen · Feb 6, 2019

For your requirement of "$result to be identical to $arr", try:

$result = array_combine(
     array_keys($arr), 
     array_map(function($v){ return $v; }, $arr)
);

Gives:

   [
     "id" => 1
     "name" => "Fred"
   ]