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


Recommendation: If you are interested in fast PHP for your WordPress site, check out this great PHP/WP benchmark-post from Kinsta, where you can get great managed WordPress hosting with the best support and performance optimizing technical addons like Redis and ElasticSearch.

The snippets story

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

$arr = array(
      'id' => 22,
      'text' => 'Lorem'
      '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:

17 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 ?

  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..

  4. This could help 🙂

    ‘text’ => ‘Lorem’
    ‘id’ => 25,
    ‘text’ => ‘ipsum’
    function get_value($val, $key) {
    global $master_arr;
    $master_arr[$val[‘text’]] = $val[‘id’];
    array_walk($arr, ‘get_value’);

  5. // Example of a rough array_map.

    $years = [2020, 2019];
    $expected_output = [2020 => 2020, 2019 => 2019];
    // Foreach way.
    $output1 = [];
    foreach ($years as $year) {
    $output1[$year] = $year;
    // Array reduce way.
    $output2 = array_reduce(
    function ($carry, $item) {
    if (!$carry) {
    return [$item => $item];
    return $carry + [$item => $item];
    echo “Input:\n”;
    echo “Expected:\n”;
    echo “Foreach: \n”;
    echo “Array Reduce: \n”;
    echo “\n”;

Leave a Reply

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