How to access the key

First idea

Taking a closer look in the documentation of array_map($callback, $arr) I realised that in truth it's array_map($callback, $arr1, $arr2, ...). Therefore one should simply write:

$arr = ['key1' => 1, 'key2' => 2, 'key3' => 3];

$res = array_map(function($value, $key) {
    return sprintf('Key "%s" has value "%s".', $key, $value);
}, $arr, array_keys($arr));

print_r($res);

// Output:
// Array
// (
//     [0] => Key "key1" has value "1".
//     [1] => Key "key2" has value "2".
//     [2] => Key "key3" has value "3".
// )

This works, but it's not preserving the keys of the original array.

Second idea

Ok what about passing the original array to the closure?

$res = array_map(function($value) use ($arr) {
    return sprintf('Key "%s" has value "%s".', key($arr), $value);
}, $arr);

// Output:
// Array
// (
//    [key1] => Key "key1" has value "1".
//    [key2] => Key "key1" has value "2".
//    [key3] => Key "key1" has value "3".
// )

This is not working because $arr is passed by value to array_map. But this approach can be fixed by passing $arr as reference and by moving the pointer every time the callback is used::

$res = array_map(function($value) use (&$arr) {
    $res = sprintf('Key "%s" has value "%s".', key($arr), $value);
    next($arr);
    return $res;
}, $arr);

// Output:
// Array
// (
//     [key1] => Key "key1" has value "1".
//     [key2] => Key "key2" has value "2".
//     [key3] => Key "key3" has value "3".
// )

Twitter