Convert php array to Javascript

I’m going to assume that the two arrays you’ve given for PHP and JS are not related, and they’re just examples of how arrays look in the two languages. Clearly you’re not going to be able to convert those sequences of letters and numbers into those city names.

PHP provides a function to convert PHP arrays into Javascript code: json_encode(). (technically, it’s JSON format; JSON stands for JavaScript Object Notation)

Use it like this:

<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>

See also the manual page I linked above for more information.

Note that json_encode() is only available in PHP 5.2 and up, so if you’re using an older version, you’ll need to use an existing one — the PHP manual page also includes comments with functions written by people who needed it. (but that said, if you’re using anything older than PHP 5.2 you should upgrade ASAP)

Leave a Comment