Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,266 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,266 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.