PHP
Rename Associative Array Keys with a Map
Discover how to efficiently rename keys in a PHP associative array using a predefined mapping array, perfect for standardizing data fields.
<?php
$userData = [
'user_id' => 101,
'full_name' => 'John Doe',
'email_address' => '[email protected]',
'registration_date' => '2023-01-15'
];
$keyMap = [
'user_id' => 'id',
'full_name' => 'name',
'email_address' => 'email',
// 'registration_date' => 'registered_at' // Optional: if you want to rename this too
];
$renamedData = [];
foreach ($userData as $oldKey => $value) {
if (isset($keyMap[$oldKey])) {
$newKey = $keyMap[$oldKey];
$renamedData[$newKey] = $value;
} else {
// Keep original key if not in map, or skip if you only want mapped keys
$renamedData[$oldKey] = $value;
}
}
echo "Original Data:
";
print_r($userData);
echo "
Renamed Data:
";
print_r($renamedData);
// Alternative using array_reduce for a more functional approach
$anotherRenamedData = array_reduce(array_keys($userData), function($carry, $key) use ($userData, $keyMap) {
$newKey = $keyMap[$key] ?? $key; // Use new key if exists, otherwise keep old
$carry[$newKey] = $userData[$key];
return $carry;
}, []);
echo "
Renamed Data (functional):
";
print_r($anotherRenamedData);
?>
How it works: This snippet shows two methods for renaming keys in an associative array. The first uses a `foreach` loop to iterate through the original array, applying a predefined `keyMap` to transform old keys into new ones. Keys not present in the map can either be retained or dropped. The second method uses `array_reduce` for a more functional approach, achieving the same result concisely.