How can I use array_map with keys and values, but return an array at the same indices (not int)?
I have an array like ['id' => 1, 'name' => 'Fred']
.
I want to call array_map
on this array and also use the key inside the function. However, when I do a return, my keys 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 it to $result
be identical $arr
in this case, but it turns my string keys into ints.
+6
source to share
2 answers
The closest you get using array_map()
is:
<?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 off creating your own function with foreach
inside.
+9
source to share