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 trialmiguel catt
1,424 PointsHow is the $item variable getting accessed and where is it coming from?
How is it that we're able to access the $item variable and insert into $pageTitle?
<?php
include("inc/data.php");
include("inc/functions.php");
if(isset($_GET["id"])) {
$id = $_GET["id"];
if(isset($catalog[$id])) {
$item = $catalog[$id];
}
}
if(!isset($item)) {
header("location:catalog.php");
exit;
}
$pageTitle = $item["title"];
$section = null;
include("inc/header.php");
?>
1 Answer
Damien Watson
27,419 PointsHi Miguel,
'$item
' is set on line 9 of your code, if '$_GET['id']
' and '$catalog[$id]
' is set:
<?php
include("inc/data.php");
include("inc/functions.php");
if(isset($_GET["id"])) {
$id = $_GET["id"];
if(isset($catalog[$id])) {
$item = $catalog[$id]; // Is set here if theres an id & catalog id
}
}
if(!isset($item)) { // if not id & catalog id, then its 'not set' (!isset)
header("location:catalog.php"); // redirect away from page
exit;
}
$pageTitle = $item["title"]; // never reaches here if not set
$section = null;
include("inc/header.php");
?>
miguel catt
1,424 Pointsmiguel catt
1,424 PointsSo does that mean I can access variables inside an if statement?
Damien Watson
27,419 PointsDamien Watson
27,419 PointsIf they are declared in the same context as what is being used, there are global and local variables. If the variable is defined in the same section as the if statement, then sure.
To clarify, if you defined a variable in the main code and then tried to access it in a function, you would have issues unless you made the variable a global.