phparraysasort

PHP asort for sorting array items by values ASC?


It is strange with asort, I want to sort the items in an array by their value,

$items = Array ( "1" => 10 , "11" => 10, "22" => 10 );

// Sort an array and maintain index association.
asort($items);

var_dump($items);

So since all values are the same, then asort shouldn't doing anything (I assume), but the result I get,

array (size=3)
  22 => string '10' (length=2)
  11 => string '10' (length=2)
  1 => string '10' (length=2)

It reverses the order!? Why?

what I want (I think it should be like this),

array (size=3)
  1 => string '10' (length=2)
  11 => string '10' (length=2)
  22 => string '10' (length=2)

Any ideas?

EDIT:

I tried with this below,

// Comparison function
private function cmp($a, $b) {
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

...

// Sort an array and maintain index association.
uasort($items, array($this, "cmp"));

But I still get the same 'error' result....


Solution

  • Since the version 4.1.0 PHP sort is not stable due to sorting algorithm, which cannot take into account both value and key. You have to use your own implementation of comparison considering key in case of equal values. For example you can modify original array values into (key, value) pairs, sort array and transform it into single dimensional back.

    $items = ["1" => 10, "11" => 10, "22" => 10];
    
    $callback = function ($a, $b) use ($callback) {
        $result = $a['value'] - $b['value'];
    
        if ($result == 0) {
            $result = $a['key'] - $b['key'];
        }
    
        return $result;
    };
    
    array_walk($items, function (&$value, $key) {
        $value = ["key" => $key, "value" => $value];
    });
    
    usort($items, $callback);
    
    $items = array_combine(array_column($items, 'key'), array_column($items, 'value'));
    
    print_r($items);