Skip to content

Instantly share code, notes, and snippets.

@alexaandrov
Last active June 7, 2018 12:10
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 alexaandrov/281e17c8048698778cbd12c0a639bb11 to your computer and use it in GitHub Desktop.
Save alexaandrov/281e17c8048698778cbd12c0a639bb11 to your computer and use it in GitHub Desktop.
Function that recursively changes the first character register of all keys in an array
<?php
/**
* Recursively changes the first character register of all keys in an array.
* @param array $array The array to work on
* @param int $case Either CASE_UPPER or CASE_LOWER (default)
* @return array Returns an array with its keys lower or uppercase.
*
* Inspired by http://php.net/manual/en/function.array-change-key-case.php
* @author Grigory Alexandrov <alexaandrov@gmail.com>
*/
function arrayChangeFirstKeyCase(array $array, $case = CASE_LOWER)
{
switch ($case) {
case CASE_LOWER:
$callback = 'lcfirst';
break;
case CASE_UPPER:
$callback = 'ucfirst';
break;
default:
throw new \Exception('Incorrect case');
}
$formattedArray = [];
foreach ($array as $key => $value) {
$key = call_user_func($callback, $key);
if (is_array($value)) {
$value = arrayChangeFirstKeyCase($value, $case);
}
$formattedArray[$key] = $value;
}
return $formattedArray;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment