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 trialJames Barrett
13,253 PointsCan somebody walk me through what this code does? I was unclear in the pevious section of PHP basics too.
<?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
Codin - Codesmite
8,600 PointsIn the following example we assume the url is "www.website.co.uk/index.php?id=1", if for example it was "index.php?id=2" the value of $_GET["id"] would be 2 instead of 1.
<?php
$flavors = array(); // Initialize empty array $flavors
$flavors[1] = "Cake Batter"; // Push "Cake Batter" to $flavors with key index 1
$flavors[2] = "Cookie Dough" // Push "Cookie Dough" to $flavors with key index 2
if (isset($_GET["id"])) { // If $_GET["id"] is set, $_GET[] is an associative array of variables stored in the url for example "www.website.co.uk/index.php?id=1"
if (isset($flavors[$_GET["id"]])) { // if $flavors[1] is set if for example the url was "www.website.co.uk/index.php?id=1"
echo $flavors[$_GET["id"]]; // echo $flavors[1] if for example the url was "www.website.co.uk/index.php?id=1"
} else { // else if $flavors[1] is not set if for example the url was "www.website.co.uk/index.php?id=1"
echo "B"; // echo "B"
}
} else { // else if $_GET["id"] is not set
echo "A"; //echo "A"
}
?>
Matthew Bilz
15,829 PointsPart one of this:
If the URL has a query string with one of the ice cream flavors, i.e. 'www.flavors.php?id=1', or the $_GET variable has been passed along to the page, then the code would execute the statement inside of the if(isset($_GET["id"])) bracket.
If not, then you would echo 'A' at the bottom of the code.
Then, if the id in the query string is either 1 or 2, then it would execute the next section of the code inside the if(isset($flavors[$_GET["id"]])), which would echo out the flavor associated with the $flavor with the id of 1 or 2, depending on the query string's value (if it's 1 or 2).
If not, then the code would echo out "b" because there is a query string, but the number is neither 1 nor 2, so there is no flavor array associated with the query id.
I hope this helps at all!
James Barrett
13,253 PointsJames Barrett
13,253 PointsAwesome, thanks!