How can PHP and JavaScript code be best separated to avoid mixing them?

To avoid mixing PHP and JavaScript code, it is best to separate them into different files or sections within the same file. This separation helps maintain code organization and readability. One common approach is to use PHP to generate the necessary JavaScript code and include it in the HTML output.

<?php
// PHP code
$data = ['apple', 'banana', 'cherry'];
?>

<script>
// JavaScript code
var fruits = <?php echo json_encode($data); ?>;
console.log(fruits);
</script>