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

Chalenge = Manipulating an Array ????

Manipulating an Array Chalenge

This block of code creates an array of ice cream flavors and displays them in ascending order. The owner of the ice cream shop would like this order changed so that the flavors are displayed in descending order instead, starting with Cookie Dough first and Jalapeno So Spicy last. Leave the $flavors array itself in the same order, but modify something else in this code block to achieve that.

<html>
<body>
<?php

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

    $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>

I really don't know where to put array_reverse()

Tried to change:

$list_html = "";    to    $list_html = array_reverse($flavors);

But it doesn't work!

Help! :)

3 Answers

David Kaneshiro Jr.
David Kaneshiro Jr.
29,247 Points

Use a different variable name for the output of the array_reverse() function, don't use $list_html. Maybe call the new array $reverse_flavors. Also make sure to call the array_reverse() function before the foreach loop.

still not working

<?php

    $list_html = "";
    $reverse_flavors = array_reverse($flavors);
    foreach($flavors as $flavor) {
        $list_html = $list_html . "<li>";
        $list_html = $list_html . $flavor;
        $list_html = $list_html . "</li>";
    }
    echo $list_html;

?>

What did i do wrong? :(

David Kaneshiro Jr.
David Kaneshiro Jr.
29,247 Points

Sorry, in the foreach loop change $flavors to $reverse_flavors.

Thanks David!

it worked!

This worked for me

<html> <body> <?php

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

?> <ul> <?php

$list_html = "";
$reverse_flavors = array_reverse($flavors);
foreach($reverse_flavors as $flavor) {
    $list_html = $list_html . "<li>";
    $list_html = $list_html . $flavor;
    $list_html = $list_html . "</li>";
}
echo $list_html;

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