Last active
June 7, 2018 12:10
-
-
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
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 | |
/** | |
* 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 <[email protected]> | |
*/ | |
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