PHP

Reorder Associative Array by Custom Key Order

Learn how to rearrange the elements of an associative PHP array based on a predefined, custom order of keys, ensuring consistent data presentation.

<?php
function reorderArrayByKeys(array $array, array $desiredKeyOrder): array {
    $reordered = [];
    // Add keys in the desired order
    foreach ($desiredKeyOrder as $key) {
        if (array_key_exists($key, $array)) {
            $reordered[$key] = $array[$key];
            unset($array[$key]); // Remove from original to find remaining
        }
    }
    // Append any remaining keys not specified in the desired order
    // This is optional, depending on whether you want to drop unspecified keys
    $reordered = array_merge($reordered, $array);

    return $reordered;
}

$userProfile = [
    'email' => '[email protected]',
    'id' => 123,
    'last_name' => 'Doe',
    'first_name' => 'John',
    'address' => '123 Main St',
    'phone' => '555-1234'
];

$displayOrder = ['id', 'first_name', 'last_name', 'email', 'phone', 'address', 'bio'];

$orderedProfile = reorderArrayByKeys($userProfile, $displayOrder);
/*
$orderedProfile will be:
[
    'id' => 123,
    'first_name' => 'John',
    'last_name' => 'Doe',
    'email' => '[email protected]',
    'phone' => '555-1234',
    'address' => '123 Main St'
]
(Note: 'bio' from $displayOrder is ignored as it wasn't in $userProfile.
If $userProfile had other keys not in $displayOrder, they would be appended at the end
due to array_merge($reordered, $array);)
*/
How it works: This function allows you to reorder an associative array according to a custom list of keys. It iterates through the `$desiredKeyOrder` array, adding corresponding key-value pairs from the original `$array` to the new `$reordered` array. Keys present in the original array but not in the `$desiredKeyOrder` are then appended at the end. This is crucial for consistent presentation of data, like displaying user profiles or configuration settings in a specific sequence.

Need help integrating this into your project?

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

Hire DigitalCodeLabs