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 trialjasonjones5
Courses Plus Student 5,571 PointsIntegrating with Paypal Stage 5 problem
I'm redoing this track so I'm clear about how to do this stuff but I came across this question and I don't get it:
I visit my flavor.php file with an extra variable in the web address, like this:
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";
}
?>
There is no extra variable in the URL and thus $_GET["id"] can't be set, so (as I see it) it should skip the code block and run the first else statement, meaning the answer would be B but it's not.
$flavors is obviously set but I can't see how it would use it if the other part of the statement can't be applied unless it's ignoring it, which is not something I've come across in any of the examples. I'm curious what I'm missing here. If someone could elaborate I'd appreciate it.
1 Answer
jasonjones5
Courses Plus Student 5,571 PointsThanks Daniel, that makes perfect sense. Didn't notice that at all and also didn't realise if/else was that flexible. Very useful.
Daniel Moreira
8,457 PointsDaniel Moreira
8,457 PointsHi Jason.
The correct answer here is A.
In the first "if" conditional you ask if the $_GET variable id is set. Since that variable isn't set, all the code inside this "if" conditional isn't executed so the server will never get to echo "B". Notice that this "else" with the echo "B" command is inside the first "if".
So the server will read the else that is related to the first "if" (not the one that is nested inside it) and the result will be A.
Hope this helps.