Quick Answer

Communicate between PHP and JavaScript.

Understanding the Issue

Modern web apps often need to pass data from server-side PHP to client-side JavaScript using JSON format.

The Problem

This code demonstrates the issue:

Php Error
// Need to pass PHP array to JavaScript

The Solution

Here's the corrected code:

Php Fixed
<?php
$data = ["name" => "John", "age" => 30];
header("Content-Type: application/json");
echo json_encode($data);
exit; // For API endpoints

// Alternative: Embed in HTML
<script>
const phpData = <?php echo json_encode($data); ?>;
console.log(phpData.name); // "John"
</script>

Key Takeaways

Use json_encode() for safe data transfer between PHP and JS.