PHP

Recursively Transform PHP Array Keys (e.g., camelCase to snake_case)

Efficiently convert keys in a PHP associative array, including nested arrays, between camelCase and snake_case for consistent data formatting, common in API integrations.

<?php
/**
 * Recursively transforms array keys between camelCase and snake_case.
 *
 * @param array $array The input array.
 * @param string $transformType 'to_snake_case' or 'toCamelCase'.
 * @return array The array with transformed keys.
 */
function transformArrayKeys(array $array, string $transformType = 'to_snake_case'): array {
    $transformedArray = [];
    foreach ($array as $key => $value) {
        $newKey = $key;
        if ($transformType === 'to_snake_case') {
            // Convert camelCase to snake_case
            $newKey = strtolower(preg_replace('/(?<!^)[A-Z]/', '_$0', $key));
        } elseif ($transformType === 'toCamelCase') {
            // Convert snake_case to camelCase
            $newKey = lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $key))));
        }

        if (is_array($value) && !empty($value)) {
            $transformedArray[$newKey] = transformArrayKeys($value, $transformType);
        } else {
            $transformedArray[$newKey] = $value;
        }
    }
    return $transformedArray;
}

$data = [
    'firstName' => 'John',
    'lastName' => 'Doe',
    'userDetails' => ['emailAddress' => '[email protected]', 'isActive' => true],
    'favoriteColors' => ['red', 'blue']
];

echo "Original Data:
";
print_r($data);

$snakeCaseData = transformArrayKeys($data, 'to_snake_case');
echo "
Snake Case Data:
";
print_r($snakeCaseData);
/* Expected output:
Array
(
    [first_name] => John
    [last_name] => Doe
    [user_details] => Array
        (
            [email_address] => [email protected]
            [is_active] => 1
        )
    [favorite_colors] => Array
        (
            [0] => red
            [1] => blue
        )
)
*/

$camelCaseData = transformArrayKeys($snakeCaseData, 'toCamelCase');
echo "
Camel Case Data:
";
print_r($camelCaseData);
/* Expected output:
Array
(
    [firstName] => John
    [lastName] => Doe
    [userDetails] => Array
        (
            [emailAddress] => [email protected]
            [isActive] => 1
        )
    [favoriteColors] => Array
        (
            [0] => red
            [1] => blue
        )
)
*/
?>
How it works: This function `transformArrayKeys` provides a powerful way to standardize array keys, which is crucial when dealing with different data sources or API conventions. It recursively traverses nested arrays, applying a transformation (either camelCase to snake_case or vice-versa) to each key. Regular expressions handle the complex conversion logic, ensuring keys are consistently formatted throughout the data structure.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs