1

very simple question. Lol i am embarassed to ask this cause i am usually very good with php but what are the ways to display html inside of php? for example:


<? if($flag): ?>
  <div>This will show is $flag is true </div>
<? endif; ?>

OR


<?
  if($flag)
    echo '<div>This will show is $flag is true </div>';
?>

I know that there are at least 2 other ways i just cannot remember them atm... Help is def. appreciated in advance!! =D

Yahel
  • 37,023
  • 22
  • 103
  • 153
rolling_codes
  • 15,174
  • 22
  • 76
  • 112
  • You should use single quotes (`'`) with echo. Double quotes (`"`) are interpreted differently and PHP is going to replace `$flag` with `$flag`s value. Use single quotes if you want the same behaviour as in your first example. – jwueller Oct 27 '10 at 12:22
  • thanks elusive made the edits – rolling_codes Oct 27 '10 at 12:24
  • 1
    [Everything you ever wanted to know about strings but were afraid to ask](http://uk2.php.net/manual/en/language.types.string.php "PHP Manual on Strings") – Gordon Oct 27 '10 at 12:26

3 Answers3

2

Here's how a heredoc could be used:

if($flag)
{
    echo <<<HTML
        <div>This will show if \$flag is true </div>
HTML;

}

If you don't want variable interpolation, you have to escape possible varnames as I have above. Alternatively, you can use a nowdoc with PHP 5.3 onwards:

if($flag)
{
    echo <<<'HTML'
        <div>This will show if $flag is true </div>
HTML;

}
Paul Dixon
  • 295,876
  • 54
  • 310
  • 348
1

You can also use a heredoc.

fire
  • 21,383
  • 17
  • 79
  • 114
0

PHP also has a nowdoc syntax that works like heredoc, but similar to single quoted strings, these doc blocks do not get parsed.

Craige
  • 2,882
  • 2
  • 20
  • 28