Dec 16, 2019 3:00 PM

Sorting an array by keys based on another array in PHP

Sorting an array by keys based on another array in PHP

In this article I will give an example how to sort an array by keys based on another array in PHP. Sometimes you may need to stick with the correct order of keys in an array. However, in PHP itself there is no such function, but it is easy to implement. Use this function to sort an array by keys based on another array:

function sortArrayByKeysArray(array &$array, array $orderArray)
{
    if (!empty($array) && !empty($orderArray)) {
        $array = array_replace(array_flip($orderArray), $array);
    }
}

For example, let's take an array with the wrong sort

$array = [
    'first_key' => 'First value',
    'third_key' => 'Third value',
    'second_key' => 'Second value',
    'fifth_key' => 'Fifth value',
    'fourth_key' => 'Fourth value',
];

and sort it in the correct order by the given array

$orderArray = [
    'first_key',
    'second_key',
    'third_key',
    'fourth_key',
    'fifth_key',
];

The array will be sorted by values in the correct order after calling this function:

sortArrayByKeysArray($array, $orderArray);

/**
[output]
array (
    'first_key' => 'First value',
    'second_key' => 'Second value',
    'third_key' => 'Third value',
    'fourth_key' => 'Fourth value',
    'fifth_key' => 'Fifth value',
)
 */

Other articles