Howto use array_map on associative arrays to change values and keys

$assoc_arr = array_reduce($arr, function ($result, $item) {
    $result[$item['text']] = $item['id'];
    return $result;
}, array());

The snippets story

I just ran into a problem using array_map on associative arrays, like the following one:

$arr = array(
   array(
      'id' => 22,
      'text' => 'Lorem'
   ),
   array(
      'id' => 25,
      'text' => 'ipsum'
   ),
);

From this array, I wanted to create another, associative array, with the following structure:

$assoc_arr = array(
   'Lorem' => 22,
   'ipsum' => 25
);

My first guess was the array_map function, but I had to realize that there is no way to manipulate the keys of the resulting array. After some googling, I discovered, that it is array_reduce you have to use to simulate array_map on associative arrays.

ps: I know, a simple foreach would have done the trick, but once on the path of functional programming, I didn’t want to leave it that fast 🙂

Tagged with:

12 thoughts on “Howto use array_map on associative arrays to change values and keys

  1. As you mentioned “a simple foreach would have done the trick”, what’s the point using array_reduce then ?
    It seems It puts complexity where there isn’t any. Do you have another example, where It is unavoidable ?
    thanks

  2. Been looking for this for a while. Like you say a foreach would suffice, but why make it easy. This is going straight on my (non-competng, private) snippets site. Thanks for spending the time

  3. First of all thank you for sharing this informative blog.. This blog having more useful information that information explanation are step by step and very clear so easy and interesting to read.. After reading this blog i am strong in this topic which helpful to cracking the interview easily..

Leave a Reply

Your email address will not be published. Required fields are marked *