Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional embed HTML between PHP code blocks?

Tags:

html

php

I'm fairly new to PHP. I started learning it like 3 weeks ago. I cannot find the answer to this question on StackOverflow, Google or Youtube. The PHP documentation to this just confuses me. To get on with the question, how does PHP code mixed in with HTML work?

<?php if (something) { ?>
    <p>Hello</p>
<?php } ?>

The p element will only display if something has a truthy value, how is this?... I thought for sure that the PHP engine ignored what was going on around the outside of the codeblocks (e.g. <?php ?>) and only parsed what happens on the inside.

The code below gets parsed by the PHP engine normally and sent to the browser without affecting any HTML elements (even though its clearly between 2 code blocks).

<?php echo $something; ?>
<p>Hello</p>
<?php echo $something; ?>

I hope I'm not going to get flamed for asking this question since a lot of people seem to understand how it works in like a tenth of second.

P.S. I asked this question in chat early and thought I understood it correctly but when I went to implement it my mind was still like, how does this work exactly? It just seems like some kind of hack to me.

like image 567
W3Geek Avatar asked Aug 20 '12 04:08

W3Geek


1 Answers

Easy now. Definitely need a php tutorial for you to start on http://www.tizag.com/phpT/

Here is what your doing:

<?php 
//Anything inside me php processes
if($something)
{
    echo "<p>something</p>";
}
//About to stop processing in php
?>
<p>Anything outside of the php statement above will just be printed to the dom</p>

Quick Note: It is good practice to separate your PHP from your HTML

<?php if ($something) { ?>  <-- where is the other {
<p>Hello</p>
<?php } ?> <-- oh I see it.
like image 178
Jared Drake Avatar answered Sep 19 '22 11:09

Jared Drake