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

Working with Get Variables and PHP tag placement.

I am on the Working with Get Variables lesson, and I understand the how and why of the If, isset, and $_GET statements. What am lost on is the following,

<p><?php } else { ?></p>

Specifically, I do not understand why the curly brace closes after the php statement, and opens after the else statement.

I have went through and looked watched the video numerous times, but no joy. Thanks in advance.

3 Answers

I was a little confused when first learning PHP as well, so I know where your coming from here:

<?php if($something == true){ ?>
    <div>This is Raw HTML that will only be rendered if the if statement is TRUE.</div>
    <div>Another HTML content</div>
<?php } else { ?>
    <div>This is Raw HTML that will only be rendered if the if statement is FALSE</div>
    <div>Another HTML element that is different and only appears if the if statement is FALSE</div>
<?php } ?>

<!-- ----------- is the same as ---------- --->

<?php if($something == true){
    echo '<div>This is HTML that will only be printed with PHP if the if statement is TRUE.</div><div>Another HTML content</div>';
 } else { 
    echo '<div>This is HTML that will only be printed with PHP if the if statement is FALSE</div><div>Another HTML element that is different and only appears if the if statement is FALSE</div>';
} ?>

So that format is a little cleaner way to be able to write php and HTML together. It allows you to write html code that is not wrapped in a php echo, which can be a lot easier to deal with when working with larger blocks of HTML code that you want to use a conditional (like an if else statement) to render different content.

Does this help?

Elliott Frazier
PLUS
Elliott Frazier
Courses Plus Student 9,647 Points

You do that sometimes when writing conditionals that contain a lot of html inside them to escape from using a ton of echo commands Example:

    <?php if($value === "success"){ ?>
      <p>you now need to enter your email:</p>
      <input type="text">
      <p>if you you like to receive email updates please check the box below</p>
      <input type="checkbox">
      ect...
    <?php } >

Riley Hilliard & Elliott Frazier thanks for the explanation. Elliot breaking it up made it clear. Really you are wrapping the } else { command in a <?php ?> so it will know when to do that line of html. Thanks again.