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?
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.
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.
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.
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 ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With