0

I'm working off the following combination of array_combine and array_map - ideally I'd like something more like an array_map_keys to map a function to rename keys. An example:

$input = array(
    'a'=>1
    'b'=>2
);
$desired_output = array(
    'prefix.a'=>1
    'prefix.b'=>2
);

function rename_keys($input) {
array_combine(
    array_map(
        function($col) {
            return 'prefix.'.$col;
        },
        array_keys($input)
    ),
    array_values($input)
);

Nathan
  • 1,396
  • 3
  • 18
  • 32
  • 3
    Did you tried anything before posting the question? If yes, post your code and the results. If no, you should start by making some attempts. – M. Eriksson Apr 08 '19 at 09:47
  • It is not possible. Renaming means - add new key, delete previous key. None of these functions can do it. `array_map` even doesn't work with keys. – u_mulder Apr 08 '19 at 09:51
  • Was tinkering and added a working example. With array_combine it's reasonably compact but was just curious if an array_map_keys existed. – Nathan Apr 08 '19 at 09:57
  • 1
    The most compact way here is really a good old `foreach`. – deceze Apr 08 '19 at 09:58

2 Answers2

1

array_combine isn't necessary. A simple foreach should be enough.

    $old = array(
        'a'=>1,
        'b'=>2
    );

    $new = array();

    foreach ($old as $key => $value) {
        $new['prefix.' . $key] = $value;
    }

    var_dump($new);

output:

array(2) {
  ["prefix.a"]=>
  int(1)
  ["prefix.b"]=>
  int(2)
}

edit; Your question has already been answered here, including benchmarks for different approches

0stone0
  • 34,288
  • 4
  • 39
  • 64
0

You just need to for loop it with $key and $value

$a = array('a'=>1,'b'=>2);
echo'<pre>';print_r($a);
$b=array();
foreach($a as $key => $value){
    $b['prefix.'.$key] = $value;
}
echo'<pre>';print_r($b);die;

Output:

$a:
Array
(
    [a] => 1
    [b] => 2
)
$b :
Array
(
    [prefix.a] => 1
    [prefix.b] => 2
)
M.Hemant
  • 2,345
  • 1
  • 9
  • 14