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

PHP mode

http://i.minus.com/iJ0hgKoNqN1SR.png

I would like an explanation of what this code is about, usually I've seen PHP written in the normal <?php ?> but this code seems to go out of PHP mode in and out.

Is this normal or is this the standard? how is this even logical? I thought PHP purpose was to dynamically output HTML.

3 Answers

Randy Hoyt has mentioned this before on the forums, that those PHP tags do need some explanation...

The idea here is that the server interprets the PHP code before it shoots back the HTML to the client (your web browser). So, if the condition is met in the if statement, then the block of code gets executed -- in this case, the PHP gets sent to the browser. Using <?php ?> tags in this wise helps to remove the need to write numerous echo statements inside of the PHP block; it allows the server to do the logical work of determining whether or not to return the HTML, and it lets the browser do the work of displaying the returned markup.

the PHP command you see there determines if the $get("status")'s value is equal to $thanks, and if so it will execute the html shown below.

<p>thanks for your email!, I&rsquo;ll be in touch shorty.!</p>

When is this style of PHP preferred? or needed when coding, or is just a convention. So basically were just trying to avoid a bunch of echos?

As I was saying before, it's helpful to keep you from needing to write echo statements all over your HTML. It keeps the logic on the server side, and lets the browser to the work of presenting the HTML. It's just a cutesy little trick; it's not particularly widely used in the real word, but you'll come across it every now and again...

Randy Hoyt
Randy Hoyt
Treehouse Guest Teacher

As you continue through the PHP course, we'll talk about separating concerns and writing clean code. It's a good practice to use multiple PHP tags in view code, where the PHP tags is mingled with HTML. Typically your code that deals with data and logic (controller and model code) will contain just one large PHP code block, while the code that deals with generating the web page (view code) will have HTML tags mingled with PHP tags. It's actually more than just a cutesy little trick: it's the proper way to structure view code to make it easier to read and maintain over time.