14

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

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 without reindexing my array.

5
  • 2
    You need to show what result you want. This works as it should. Aug 26, 2014 at 19:15
  • 3
    From the documentation "If the array argument contains string keys then the returned array will contain string keys if and only if exactly one array is passed. If more than one argument is passed then the returned array always has integer keys." (emphasis mine)
    – Patrick Q
    Aug 26, 2014 at 19:16
  • array_map() is an inappropriate tool for this job. Show us what you actually want to do with this daya. Mar 8, 2020 at 10:22
  • This question's problem statement is Unclear; therefor this page should be closed or edited by the asker. Nov 15 at 23:18
  • array_map() does not kill keys if you just pass in the array. 3v4l.org/HWH9C If you pass in multiple arrays, of course, it cannot know which keys to preserve. 3v4l.org/KJbaV This seems like an XY Problem. Nov 16 at 1:14

6 Answers 6

25

For your requirement of "I want to call array_map" and "$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"
   ]

But heh, if all you want is identical arrays, then nothing beats this code:

$result = $arr;
1
  • 3
    This is not a good generic solution because the transformation function does not have access to the current key.
    – Walf
    Mar 24, 2022 at 7:25
14

The closest you will get using array_map() is this:

<?php
$arr = array('id'=>1,'name'=>'Jon');

$callback = function ($key, $value) {
    return array($key => $value);
  };

$arr = array_map( $callback, array_keys($arr), $arr);
var_dump($arr);
?>

Gives:

   [
     [
       "id" => 1
     ],
     [
       "name" => "Jon"
     ]
   ]

You will be better creating your own function with a foreach inside.

1
  • The question asks for original keys, not nested arrays with integer keys.
    – Walf
    Jun 23 at 6:42
4

What you need is array_walk(). Try this code:

$arr = array('id' => 1, 'name' => 'Fred');
array_walk(
    $arr,
    function (&$value, $key) {
        // do stuff
    }
);
print_r($arr);

Unfortunately, it cannot change the keys but you can change the values if your callback uses them by reference.

If you have to change the keys too, check my other answer regarding reindexing with array_walk().

2

Based on @Jannie Theunissen answer the correct way of getting an array_map working with key for comparing and assigning values based on second array for example is:

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

Or for optimized alternative:

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

And with a comparison array value:

$compareArray = [/*same structure as $arr but with specific values*/];
$keys = array_keys($arr);
$result = array_combine(
 $keys, 
 array_map(function($v, $key) use ($compareArray) { 
              // recursive can be achieved here passing $v and $compareArray[$key]
              return $compareArray[$key]; 
           }, $arr, $keys)
);
0

The idea is quite simple. You need to use keys inside your array_map() function.

For this purpose we add two arrays: the first one array_keys($array) we pass the keys of our major array and the second one $array is the needed array.

array_map(function($key, $value) {

       // use your key here ...
       return $processed_value;

    }, array_keys($array), $array)

From now on: you can use the $key as a value from first param and $value as a second param.

3
  • 3
    it would be nice if you can add some explanation words to your solution
    – mooga
    Sep 24, 2020 at 14:57
  • 2
    right you are. thanks for your comment. i've updated my solution with description.
    – muinh
    Sep 24, 2020 at 20:44
  • This returns an array with integer keys, which is the problem that is meant to solved.
    – Walf
    Mar 24, 2022 at 7:27
0

I don't think I came up with this, but I don't remember where I got it, either.

This function is generic, has the same variadic signature as array_map(), but preserves the keys of the first array passed, and the callback gets the current key as the first arg and the value(s) as the subsequent arg(s), like function ($k, $v, $v2, ..., $vn) {, (whereas array_map() only gets the array values).

function array_map_assoc(callable $callback, array $array, array ...$arrays) {
    $keys = array_keys($array);
    array_unshift($arrays, $keys, $array);
    return array_combine($keys, array_map($callback, ...$arrays));
}

Example: https://3v4l.org/9XQF9

Other examples here have function ($v, $k) { as the callback signature but they're limited to one input array, and it doesn't make sense to have the key in the middle of the values when accepting multiple input arrays.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.