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?
The issue arises with sorting equal values in the array. Take the array:
Calling
asort($arr, SORT_NUMERIC)on this array will reverse the array. Hence, the lines of code:will put the array back in the original order.
So, adding in one value that’s higher with change the array as such:
will yeild:
while
will yeild:
Hopefully this sheds some light on the issue …