Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP PHP Arrays and Control Structures PHP Arrays Mixing and Sorting

Ezell Frazier
Ezell Frazier
22,110 Points

Testing out the answer choices for this question does not produce the desired results. rsort works, but not the others.

Question:

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

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

Options:

  • sort
  • asort
  • krsort
  • ksort
  • arsort
<?php

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

rsort($colors);

for ($index = 0; $index < count ($colors); $index ++) {
    echo $colors[$index] . "\n";
}

//Yellow
//Red
//Purple
//Orange
//Green
//Blue
//Black

Everything else will produce other results not matching the desired output.

I've ran the code online using PHP Sandbox

Bára Paulátová
Bára Paulátová
3,583 Points

Hello Ezell,

have you tried this?

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

arsort($colors);

foreach ($colors as $color){
  echo $color;
}
?>
Cris Pijper
Cris Pijper
11,743 Points

rsort works, because that is the answer to the question.

This is an array with random colors: $colors = array("Red", "Orange", "Yellow", "Green", "Blue", "Purple", "Black");

Using the rsort function will sort the array in reverse alphabetical order.

1 Answer

Ezell Frazier
Ezell Frazier
22,110 Points

Hi Bára Paulátová, your solution worked. I forgot the sorting method would not be noticeable unless I used a for each loop instead of a standard for loop.

Thanks to you and Cris Pijper!