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 Build a Basic PHP Website (2018) Adding a Basic Form Forms and User Input

Eitay Zilbershmidet
Eitay Zilbershmidet
3,942 Points

Help with quiz, fail to understand this...

I visit my flavor.php file with an extra variable in the web address, like this: http://localhost/flavor.php?id=1 If my flavor.php file has the code shown below, what does it output? <?php

$flavors = array();

$flavors[1] = "Cake Batter";

$flavors[2] = "Cookie Dough";

if (isset($_GET["id"])) {

if (isset($flavors[$_GET["id"]])) {

    echo $flavors[$_GET["id"]];

} else {

    echo "B";

}

} else {

echo "A";

}

?>

2 Answers

Jason Anders
MOD
Jason Anders
Treehouse Moderator 145,860 Points

Hey Eitay,

I'll see if I can explain why the answer is "B" --> Let's break down the code:

<?php

$flavors = array();

$flavors[1] = "Cake Batter";

$flavors[2] = "Cookie Dough";

if (isset($_GET["id"])) {

    if (isset($flavors[$_GET["id"]])) {

        echo $flavors[$_GET["id"]];

    } else {

        echo "B";

    }

} else {

    echo "A";

}

?>

So, if you add the extra variable in the Web Address (this would be a GET request, as a GET request is passed in through the URL). The first if statement will return TRUE because the GET variable is now set. From this we now know that the second else statement in the code will not be executed, as this is the else statement for the first if statement (and that has returned TRUE, so now we move to inside of that first if statement.

Now the second if statement is checking to see if the flavor id passed in is set to one of the flavor IDs in the $flavor array. Right now, there are only 2 items added to that arrary with a set ID. So, we have an ID with 1 and and ID with 2. However, 9 is being passed into the URL GET request, so it checks and the first if says "yes it's set", but the second if says "no, there is no 9 here" and throws it to the else statement for that if statement that has returned FALSE. Therefore, that else gets executed and "B" is echoed out.

I hope that helps to make sense. Keep coding! :dizzy:

Eitay Zilbershmidet
Eitay Zilbershmidet
3,942 Points

I had to reed it many times but now I get it. Thank you so much for the answer :)