Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP sorting issue, arsort vs asort + array_reverse

Tags:

php

sorting

I was recently working on one of the project euler problem sets and came across this strange issue. I've solved the problem correctly with the first solution, but I don't know why the other version does not work as expected.

Here is the code that works:

asort($card_count, SORT_NUMERIC);
$card_count = array_reverse($card_count, true);

And here is the code that does not:

arsort($card_count, SORT_NUMERIC);

This is the only line i change and it makes a huge difference in the end result. Any ideas whats up with this?

like image 380
majic bunnie Avatar asked Jul 23 '12 19:07

majic bunnie


People also ask

What is Asort () and arsort ()?

Definition and UsageThe arsort() function sorts an associative array in descending order, according to the value. Tip: Use the asort() function to sort an associative array in ascending order, according to the value. Tip: Use the krsort() function to sort an associative array in descending order, according to the key.

What is Asort and ksort?

In its place are asort() and ksort(), which are very similar- asort() sorts an array by its values, whereas ksort() sorts an array by its keys.

What is Asort PHP?

The asort() function sorts an associative array in ascending order, according to the value. Tip: Use the arsort() function to sort an associative array in descending order, according to the value. Tip: Use the ksort() function to sort an associative array in ascending order, according to the key.


1 Answers

The issue arises with sorting equal values in the array. Take the array:

$arr = array(
    'a' => 1,
    'b' => 1,
    'c' => 1,
    'd' => 1
);

Calling asort($arr, SORT_NUMERIC) on this array will reverse the array. Hence, the lines of code:

asort($arr, SORT_NUMERIC);
$arr = array_reverse($arr, true);

will put the array back in the original order.

So, adding in one value that's higher with change the array as such:

$arr = array(
    'a' => 1,
    'b' => 1,
    'c' => 2,
    'd' => 1
);

asort($arr, SORT_NUMERIC);
$arr = array_reverse($arr, true);

will yeild:

Array
(
    [c] => 2
    [a] => 1
    [b] => 1
    [d] => 1
)

while

arsort($arr, SORT_NUMERIC);

will yeild:

Array
(
    [c] => 2
    [d] => 1
    [b] => 1
    [a] => 1
)

Hopefully this sheds some light on the issue ...

like image 133
keithhatfield Avatar answered Oct 21 '22 03:10

keithhatfield