Home >Web Front-end >JS Tutorial >How Can I Convert a PHP Array to a JavaScript Array?
PHP Array Conversion to JavaScript
In this instance, it's crucial to note that the specified PHP and JavaScript arrays are unrelated and merely exemplify how arrays manifest in each language. Transforming character and number sequences into the provided city names is not feasible.
PHP features the json_encode() function for converting PHP arrays into JavaScript. However, json_encode() can only be utilized with PHP 5.2 and later versions. If an older version of PHP is being used, consider employing an existing function, which can be found in the PHP manual page.
To employ json_encode(), follow these steps:
<script type='text/javascript'> <?php $php_array = array('abc','def','ghi'); $js_array = json_encode($php_array); echo "var javascript_array = ". $js_array . ";\n"; ?> </script>
Refer to the PHP manual page for further details and alternative functions if using a PHP version earlier than 5.2.
The above is the detailed content of How Can I Convert a PHP Array to a JavaScript Array?. For more information, please follow other related articles on the PHP Chinese website!