Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would arsort() make a central value as the first?

Tags:

arrays

php

While learning PHP at teamtreehouse.com I came across this question:

$colors = array("Red", "Orange", "Yellow", "Green", "Blue", "Purple", "Black");

Which function will sort the array so the first element is "Yellow"?

The answer to the question is arsort(), but I can't understand why, because the PHP man says:

arsort — Sort an array in reverse order and maintain index association

I understand from the man that arsort() will just reverse the order, so that Black will become first instead of last, but then, why does the Treehouse question answer says Yellow will be first?

Might it be a authors mistake in the question? Thanks.

Note: I tried to create a headline useful for people with similar confusion.


1 Answers

Both asort and arsort sort the input array (alphabetically in this case), it's just a matter of which order then are sorted in.

asort — Sort an array and maintain index association

arsort — Sort an array in reverse order and maintain index association

So it's not just a simple array reversal like array_reverse, it sorts them too.

like image 107
Alexander O'Mara Avatar answered Oct 25 '25 11:10

Alexander O'Mara



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!