What role does json_encode play in efficiently handling data transfer between PHP and JavaScript?

json_encode is used to convert a PHP array or object into a JSON string, which is a lightweight data interchange format. This allows for efficient data transfer between PHP and JavaScript as JSON is easily readable and parsable by both languages. By using json_encode in PHP to encode data before sending it to JavaScript, we ensure that the data is in a format that can be easily manipulated and displayed on the client-side.

<?php
$data = array("name" => "John", "age" => 30, "city" => "New York");
$json_data = json_encode($data);
echo "<script> var jsonData = $json_data; </script>";
?>