In the given examples, what are the different ways to correctly echo a PHP variable inside JavaScript code?
When echoing a PHP variable inside JavaScript code, it is important to ensure that the variable is properly formatted and enclosed within quotation marks. One common way to achieve this is by using PHP's `json_encode()` function to encode the variable as a JSON string. Another approach is to use PHP to directly output the variable value within a JavaScript script tag.
<?php
$php_variable = "Hello, World!";
?>
<script>
// Method 1: Using json_encode()
var js_variable = <?php echo json_encode($php_variable); ?>;
console.log(js_variable);
// Method 2: Directly outputting the variable value
var js_variable2 = '<?php echo $php_variable; ?>';
console.log(js_variable2);
</script>