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

miguel catt
miguel catt
1,424 Points

How 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
Damien Watson
27,419 Points

Hi 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
miguel catt
1,424 Points

So does that mean I can access variables inside an if statement?

Damien Watson
Damien Watson
27,419 Points

If 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.