- PHP

How to Mix PHP with HTML

If your file is saved in .php format, you can write plain HTML in it and open multiple blocks with PHP code inside.

You can’t write PHP inside your HTML file, but you can do the opposite, so make your PHP file.

index.php

<b>Some HTML code</b>

<?php

// some PHP code

?>

<i>And again, some HTML</i>

Remember, if possible, separate your PHP logic from HTML content. Mixing PHP and HTML everywhere will make it harder to read and develop your application. In developer’s slang, it’s so-called “spaghetti code”. Working with something like that is really nasty, so read about MVC or at least separate your logic to external files with requie_once, include, etc.

Example of HTML and PHP Mix:

yourfilename.php

<?php 

$devices = ['PC', 'Mouse', 'Keyboard', 'Printer', 'Headphones'];

?>

<b>Required devices:</b>

<ul>
    <?php foreach($devices as $device): ?>
        <li><?php echo $device; ?></li>
    <?php endforeach; ?>
</ul>

Output:

Required devices:
  • PC
  • Mouse
  • Keyboard
  • Printer
  • Headphones