143

I would like to embed HTML inside a PHP if statement, if it's even possible, because I'm thinking the HTML would appear before the PHP if statement is executed.

I'm trying to access a table in a database. I created a pulldown menu in HTML that lists all the tables in the database and once I select the table from the pulldown, I hit the submit button.

I use the isset function to see if the submit button has been pressed and run a loop in PHP to display the contents of the table in the database. So at this point I have the complete table but I want to run some more queries on this table. Hence the reason I'm trying to execute more HTML inside the if statement. Ultimately, I'm trying to either update (1 or more contents in a row or multiple rows) or delete (1 or more rows) contents in the table. What I'm trying to do is create another pulldown that corresponded to a column in a table to make the table search easier and radio buttons that correspond to whether I'd like to update or delete contents in the table.

IMSoP
  • 89,526
  • 13
  • 117
  • 169
  • 3
    See here for a solution http://php.net/manual/en/control-structures.alternative-syntax.php – puk Mar 20 '12 at 15:16

7 Answers7

424
<?php if($condition) : ?>
    <a href="http://yahoo.com">This will only display if $condition is true</a>
<?php endif; ?>

By request, here's elseif and else (which you can also find in the docs)

<?php if($condition) : ?>
    <a href="http://yahoo.com">This will only display if $condition is true</a>
<?php elseif($anotherCondition) : ?>
    more html
<?php else : ?>
    even more html
<?php endif; ?>

It's that simple.

The HTML will only be displayed if the condition is satisfied.

Frank Farmer
  • 38,246
  • 12
  • 71
  • 89
47

Yes,

<?php if ( $my_name == "someguy" ) { ?> 
    HTML GOES HERE 
<?php } ?>
Danish Adeel
  • 728
  • 4
  • 11
  • 27
jgallant
  • 11,143
  • 1
  • 38
  • 72
17

Yes.

<?php if ($my_name == 'someguy') { ?>
        HTML_GOES_HERE
<?php } ?>
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
chaos
  • 122,029
  • 33
  • 303
  • 309
3

Using PHP close/open tags is not very good solution because of 2 reasons: you can't print PHP variables in plain HTML and it make your code very hard to read (the next code block starts with an end bracket }, but the reader has no idea what was before).

Better is to use heredoc syntax. It is the same concept as in other languages (like bash).

 <?php
 if ($condition) {
   echo <<< END_OF_TEXT
     <b>lots of html</b> <i>$variable</i>
     lots of text...
 many lines possible, with any indentation, until the closing delimiter...
 END_OF_TEXT;
 }
 ?>

END_OF_TEXT is your delimiter (it can be basically any text like EOF, EOT). Everything between is considered string by PHP as if it were in double quotes, so you can print variables, but you don't have to escape any quotes, so it very convenient for printing html attributes.

Note that the closing delimiter must begin on the start of the line and semicolon must be placed right after it with no other chars (END_OF_TEXT;).

Heredoc with behaviour of string in single quotes (') is called nowdoc. No parsing is done inside of nowdoc. You use it in the same way as heredoc, just you put the opening delimiter in single quotes - echo <<< 'END_OF_TEXT'.

Marki555
  • 6,434
  • 3
  • 37
  • 59
  • Thank you very much for reminding me of this. Heredoc is extremely helpful for more complex HTML with multiple conditions, and much easier than escaping attributes and quotes! – UTCWebDev Aug 30 '16 at 14:42
  • `(the next code block starts with an end bracket }` is a *very* strange reasoning. This very `{` brace can be clearly seen **right above** the code block, so it didn't go anywhere. All you did is just add a lot of `echo <<< END_OF_TEXT` that indeed gets the way. So instead of just [plain PHP/HTML template](https://phpize.online/sql/mysql57/undefined/php/php81/80522304c200b059379200428b912528/) you've got **exactly the same** but [with HEREDOC added everywhere](https://phpize.online/sql/mysql57/undefined/php/php81/85553fe7c9fb515ddebafda654d53cbb/). What gives? – Your Common Sense Feb 07 '23 at 07:18
  • @YourCommonSense not sure how todays code editors handle separate php blocks `` with html in between, but I guess it could be issue (in syntax highlighting) back in 2016. – Marki555 Feb 07 '23 at 14:07
1

So if condition equals the value you want then the php document will run "include" and include will add that document to the current window for example:

`

<?php
$isARequest = true;
if ($isARequest){include('request.html');}/*So because $isARequest is true then it will include request.html but if its not a request then it will insert isNotARequest;*/
else if (!$isARequest) {include('isNotARequest.html')}
?>

`

Fast Login
  • 19
  • 2
-1
<?php if ($my_name == 'aboutme') { ?>
    HTML_GOES_HERE
<?php } ?>
govindak
  • 388
  • 5
  • 21
-1

I know this is an old post, but I really hate that there is only one answer here that suggests not mixing html and php. Instead of mixing content one should use template systems, or create a basic template system themselves.

In the php

<?php 
  $var1 = 'Alice'; $var2 = 'apples'; $var3 = 'lunch'; $var4 = 'Bob';

  if ($var1 == 'Alice') {
    $html = file_get_contents('/path/to/file.html'); //get the html template
    $template_placeholders = array('##variable1##', '##variable2##', '##variable3##', '##variable4##'); // variable placeholders inside the template
    $template_replace_variables = array($var1, $var2, $var3, $var4); // the variables to pass to the template
    $html_output = str_replace($template_placeholders, $template_replace_variables, $html); // replace the placeholders with the actual variable values.
  }

  echo $html_output;
?>

In the html (/path/to/file.html)

<p>##variable1## ate ##variable2## for ##variable3## with ##variable4##.</p>

The output of this would be:

Alice ate apples for lunch with Bob.
Bruce
  • 1,039
  • 1
  • 9
  • 31
  • That's not a template system but a self-deception. Using a template system doesn't mean a conditional statement shouldn't be used in the template. – Your Common Sense Dec 24 '22 at 10:19
  • I vastly disagree with you. A template system does not require a framework of any kind. In php a template system is any system that allows you to separate your code logic from your HTML markup. If there are conditional statements in your template, you have no separated the HTML markup from the code logic. – Bruce Feb 04 '23 at 20:16
  • It's not about agreement or disagreement :) It's about real life. In 20 years, I've been engaged in this kind of conversation dozens, if not hundreds, times. Strangely, this kind of theoretical templating is quite appealing. But easily curable. Just try to implement your approach for a more or less viable template, that contains at least one loop and one condition, like a list of site users. And you will see that in pursue of eliminating the logic from HTML you'll end up in HTML leaking into your logic, and/or splitting HTML into billion small bits, making it maintenance nightmare. – Your Common Sense Feb 05 '23 at 06:18
  • I have used this exact type of code in incredibly complex applications with foreach loops, while loops, for loops, if then statements, database calls and multiple conditions I have never seen a problem. *shugs* – Bruce Feb 06 '23 at 20:59
  • So it seems you have each template split into many small files, just like that line shown in your answer. So it means that you have got all the *markup logic* leaked into the code logic. Which is exactly opposite to your intentions. For example, you cannot work with entire design in a single file. And in case you need to fix some HTML tag, you will have to browse through dozens small files. A nightmare. – Your Common Sense Feb 07 '23 at 05:28
  • Not to mention that you have to write a lot of laborious code for the simplest operation. Compare with Twig: `{% if var1 == 'Alice' %}

    {{ var1 }} ate {{ var2 }} for {{ var3 }} with {{ var4 }}.

    {% endif %}`. One line in one file, as opposed to a dozen lines split between several files.
    – Your Common Sense Feb 07 '23 at 05:30
  • and now look at it form the opposite side of things. You are working on a huge project that you have taken over from someone else. You are required to change the html theme. The new theme you are using requires you to add new classes and ids to all your

    tags and all your

    tags. Instead of finding all of them in an html folder, now you have to search every php file to find what functions are running loops containing

    and

    tags, search within each file to find the functions, then change them.
    – Bruce Feb 07 '23 at 16:52
  • Now that may seem easy, but with ids you are going to have to figure out which function goes to which page so you can add the right ids specific to that page and if that same function is being used on multiple pages, now you have to write more logic to switch the id based on the page in question. – Bruce Feb 07 '23 at 16:56
  • The code in my answer is perfectly valid and actually works, no one is actually disputing that it works. So this entire thread is pointless. In your own words "its simpler" to do things the way you suggest. That doesn't make other ways of doing things wrong. – Bruce Feb 17 '23 at 09:01