How can PHP arrays be accessed via JavaScript and what are the potential pitfalls in doing so?

To access PHP arrays in JavaScript, you can encode the array into JSON using the `json_encode()` function in PHP and then echo it out as a JavaScript variable. This allows you to access the array data in JavaScript. However, be cautious of potential security risks such as exposing sensitive data or executing malicious code if the array contains user input.

<?php
// PHP array
$myArray = array("apple", "banana", "cherry");

// Encode PHP array to JSON
$jsonArray = json_encode($myArray);

// Echo JSON as JavaScript variable
echo "<script>var jsArray = $jsonArray;</script>";
?>