Dec 23, 2019 7:00 AM

Sorting an array by values based on another array in PHP

Sorting an array by values based on another array in PHP

In this article I will give an example how to sort an array by values based on another array in PHP. Sometimes you may need to stick with the correct order of values 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 values based on another array:

function sortArrayByValuesArray(array &$array, array $orderArray, $strict = null)
{
    if (!empty($array) && !empty($orderArray)) {
        $ordered = [];
        foreach ($orderArray as $item) {
            $search = !is_null($strict) ? array_keys($array, $item, $strict) : array_keys(preg_grep('#' . $item . '#', $array));
            if (!empty($search)) {
                foreach ($search as $key) {
                    $ordered[$key] = $array[$key];
                    unset($array[$key]);
                }
            }
        }

        $array = array_merge($ordered, $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 value',
    'Second value',
    'Third value',
    'Fourth value',
    'Fifth value',
];

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

sortArrayByValuesArray($array, $orderArray, true);

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

You can also use regular expressions when sorting in this function. For example, let's sort the same array by values in the desired order:

$orderArray = [
    '^Fi',
    'Second value',
    'Third value',
    'Fourth value',
];

In the resulting array, the values that begin with "Fi" first follow (according to the regular expression):

sortArrayByValuesArray($array, $orderArray);

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

Other articles