How to write PHP inside JavaScript

Writing PHP code in JavaScript usually isn’t the most elegant solution in the entire universe, but it does the job.

If you need it for some reason, you can easily open the <?php ?> block inside your JavaScript code as long as it is placed in your HTML file. With this method you can easily:

  • Pass variables from PHP to JavaScript.
  • Pass some PHP data to JavaScript external files (for example, you can use the PHP data as a JavaScript’s function argument).
  • Use JavaScript’s function such as console.log with PHP code.



$calculation = 2 * 5;


  document.write(<?php echo $calculation; ?>);

Output: 10