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 Enhancing a Simple PHP Application Refactoring the Codebase Manipulating an Array

Unable to sort

Hi, I have tried asort,ksort,krsort. but nothing is working. why?

index.php
<html>
<body>
<?php

$flavors = array(
        "Jalapeno So Spicy",
        "Avocado Chocolate",
        "Peppermint",
        "Vanilla",
        "Cake Batter",
        "Cookie Dough"
    );

?>
<ul>
<?php
krsort($flavors);
    $list_html = "";
    foreach($flavors as $flavor) {
        $list_html = $list_html . "<li>";
        $list_html = $list_html . $flavor;
        $list_html = $list_html . "</li>";
    }
    echo $list_html;

?>
</ul>
</body>
</html>

2 Answers

Shane Meikle
Shane Meikle
13,188 Points

Your array doesn't have a key associated with it, so the types you are using wont work. Just use regular sort.

sort($flavors);

That should work.

Jeff Lemay
Jeff Lemay
14,268 Points

The correct function is array_reverse and requires you to set a new variable for the array. So you'll want to run the function on your flavors array and set it into a new variable, I called mine $flavors_r for "flavors reversed". Then you'll need to adjust the foreach loop to use your new $flavors_r array instead of $flavors.

<?php
$flavors_r = array_reverse($flavors);
    $list_html = "";
    foreach($flavors_r as $flavor) {
        $list_html = $list_html . "<li>";
        $list_html = $list_html . $flavor;
        $list_html = $list_html . "</li>";
    }
    echo $list_html;
?>
Jeff Lemay
Jeff Lemay
14,268 Points

In reality, you would not need to set the reversed array into a new variable but for the challenge it is required. You could just overwrite your original array with the reversed order.