简体   繁体   中英

php syntax for big block of echo <?php if(1): ?> html<?php endif; ?> correct way

Well most is in the title. I wonder if it's supposed to be that way or i can do the same without an if(1) condition I'm doing this because my website pages are all as php includes.

Thank you all

Answer retained:

Okay basically the way to do it is simply to include('file.php') as it will be considered out of the current <?php ?> environment.

Putting

<?php if(1): ?>
    ...
<?php endif; ?>

around your HTML code in a PHP file will have no effect on the result. You will still be able to include the file without it.

You can think of it like the "default mode" for a PHP file is that it contains HTML content. You only need to add <?php ?> tags if you want to add PHP code. If you're just putting HTML code in a PHP file, they're unnecessary.

The beauty of PHP is that you can move "in" and "out" of PHP very easily. You can do the following without issues:

<?PHP 
if(whatever) {
?>

your HTML

<?php
include('whatever.php');
?>

more HTML

<?PHP
}
?>

To build on Zak's answer:

You can also use PHP to echo out things that aren't PHP... as long as you quote it appropriately.

<?php 

//HTML 
while ($x < 5) {
 echo "<p> this is html that you can wrap with html tags! </p>";
 $x++;
}

//Javascript
echo "<script type='text/javascript'>
          some javascript code
       </script>"
?>

Although, it's less confusing to just end the php tag to keep things separate.

And you can even use php as you want within html or javascript as long as you put the tags, and as long as the file is saved as a .php file (so PHP can be processed on the server).

Ex:

<script type="text/javascript">
    //set a javascript image array to a php value
    var imgArray = [<?php echo implode(',', getImages()) ?>];
</script>

But if you want to do this the other way around (IE, assign a browser-compiled value, such as a javascript value to a php value), you'll need to use AJAX.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM