Created
June 28, 2019 02:54
-
-
Save vardius/650367e15abfb58bcd72ca47eff096ca to your computer and use it in GitHub Desktop.
Applies the callback to the keys of the given array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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