lethalMango
lethalMango

Reputation: 4491

PHP Easy way to combine PHP if statement with HTML

This probably might be a silly question, but what I am trying to do is to make an if statement to do the following:

<?php if ($_SESSION['login'] == true) { ?>
Display this HTML code (without converting it to PHP echos
<?php } else { ?>
Display this instead
<?php } ?>

Or will I need to echo, and in turn escape all the required characters in order to do what I am after.

Thanks

Upvotes: 1

Views: 1704

Answers (5)

red-X
red-X

Reputation: 5128

Yes, it works.

<?php if ($_SESSION['login'] == true) { ?>
   <span>hello</span>
<?php } else { ?>
   <span>going already?</span>
<?php } ?>

Upvotes: 1

Michael Low
Michael Low

Reputation: 24506

Anything not in PHP tags will be outputted as HTML anyway, so your original code will work fine.

<?php if ($_SESSION['login'] == true) { ?> 
<a href="logout.html">Log Out</a> 
<?php } else { ?> 
<a href="login.html">Login</a>  
<?php } ?>

Upvotes: 1

Phill Pafford
Phill Pafford

Reputation: 85298

Look into the HEREDOC or NOWDOC syntax

<?php 
if ($_SESSION['login']) { 
   $html =<<<HTML
Add HTML here
HTML;
   echo $html;
} else { 
   $other_html =<<<'OTHERHTML'
Add HTML here
OTHERHTML;
   echo $other_html;
?>

Upvotes: 1

Konrad Rudolph
Konrad Rudolph

Reputation: 545528

Just try it out. But for the record, this works. And is in fact an idiomatic way of solving this.

<?php if ($_SESSION['login']) { ?> 
  <p>Display this HTML code</p>
<?php } else { ?> 
  <p>Display this instead</p>
<?php } ?>

Indented for readability (however, this messes with the HTML structure indentation so maybe it’s not appropriate).

Alternatively, the following style is often used because the lone brace at the end gets lonely:

<?php if ($_SESSION['login']): ?> 
  <p>Display this HTML code</p>
<?php else: ?> 
  <p>Display this instead</p>
<?php endif; ?>

(In both cases I’ve removed the == true from the conditional because it’s utterly redundant. Don’t write == true.)

Upvotes: 8

piddl0r
piddl0r

Reputation: 2449

you can also use if and endif

<?php if ( expression ) : ?>
<p>some message here</p>
<?php else : ?>
<p>other message</p>
<?php endif ?>

Upvotes: 1

Related Questions