Skip to content

Instantly share code, notes, and snippets.

@vardius
Created June 28, 2019 02:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vardius/650367e15abfb58bcd72ca47eff096ca to your computer and use it in GitHub Desktop.
Save vardius/650367e15abfb58bcd72ca47eff096ca to your computer and use it in GitHub Desktop.
Applies the callback to the keys of the given array
<?php
function array_map_keys(callable $callback, array $array) {
return array_merge([], ...array_map(
function ($key, $value) use ($callback) { return [$callback($key) => $value]; },
array_keys($array),
$array
));
}
$array = ['a' => 1, 'b' => 'test', 'c' => ['x' => 1, 'y' => 2]];
$newArray = array_map_keys(function($key) { return 'new' . ucfirst($key); }, $array);
echo json_encode($array); // {"a":1,"b":"test","c":{"x":1,"y":2}}
echo json_encode($newArray); // {"newA":1,"newB":"test","newC":{"x":1,"y":2}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment