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.


<b>Some HTML code</b>


// 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:



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


<b>Required devices:</b>

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


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