Stable Sorting Functions in PHP 8.0

PHP provides various functions to sort an array, such as sort, asort, ksort, etc. In versions prior to PHP 8.0, all PHP sorting functions are unstable. This means that the order of equal elements is not guaranteed.

Since 8.0, all PHP sorting functions are stable. It guarantees that elements that are equal to each other aren’t reordered and the order of these elements remains the same as they had in the original array.

Let’s say we have associative array. We can use asort function to sort an array and maintain indices association with the corresponding elements.

<?php

$array = [14 => 3, 85 => 2, 35 => 7, 70 => 2, 45 => 7, 25 => 2, 55 => 3];
asort($array);

print_r($array);

Example will output:

Array
(
    [85] => 2
    [70] => 2
    [25] => 2
    [14] => 3
    [55] => 3
    [35] => 7
    [45] => 7
)

The elements were arranged from smallest to largest. Elements that are equal to each other, such as (14 => 3) and (55 => 3), preserved the same order as they had in the original array.

Leave a Comment

Your email address will not be published. Required fields are marked *