Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

PHP Build a Simple PHP Application Creating the Menu and Footer Adding Active States to the Navigation

What if there is no variable in page?

Ok I tried to work on this task and if I don't set any variable to index.php browser gives me an error, how can I tell it just not to show anything in code if there is no variable? I tried with else function but no luck?

1 Answer

// Check to see if a variable is set
if (isset($my_variable)) {
   echo 'Set';
} else {
   echo 'Not Set';
}

Ok, but I need to check for variable too, is there a shorter way than this

<?php
if (isset($section)) {
if ($section == "shirts") { 
echo 'on'; 
}
} 
else { 
echo ''; 
} 
?>

In this IF clause, if the first condition is TRUE, meaning that the variable $section is set, then it will check the second condition to see if $section == "shirts".

if (isset($section) && $section == "shirts") {
   echo 'on'; 
} else { 
   echo ''; 
} 

Thank you!

Hi Ivan,

This was the code I used if you want to compare to your own:

<li class="shirts<?php if ( isset($section) && $section == "shirts") { echo " on"; } ?>"><a href="shirts.php">Shirts</a></li>
<li class="contact<?php if ( isset($section) && $section == "contact") { echo " on"; } ?>"><a href="contact.php">Contact</a></li>

There's no need to have the else block where you echo out an empty string.

Oh, thank you, that is useful :)