PHP sorting problem, arsort vs asort + array_reverse

I recently worked on one of the project euler problem sets and ran into this strange problem. I solved the problem correctly with the first solution, but I do not 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 that I am changing, and it is of great importance in the final result. Any ideas what comes up with this?

+7
source share
1 answer

The problem occurs when sorting equal values ​​in an array. Take an array:

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

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

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

will return the array to its original order .

So, adding the value above to one value with changing the array as such:

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

will look:

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

but

 arsort($arr, SORT_NUMERIC); 

will look:

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

Hope this sheds light on the problem ...

+4
source

All Articles