How can I use array_map with keys and values, but return an array with the same indexes (not int)? How can I use array_map with keys and values, but return an array with the same indexes (not int)? php php

How can I use array_map with keys and values, but return an array with the same indexes (not int)?


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;


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.


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

Unfortunally it works not when you try to change the keys. But you can change the values when you pass them by refference.

If you have to change the keys too, check Question to array_walk-change-keys and the first answer: