Update – 1 August 2013:
There are lots of suggestions in the comments that are better than my original solution. Also, with 5 years of hindsight, I’d approach it differently anyway! The way I’d do this now would be as follows:
[sourcecode language=”php”]
<script type="text/javascript">
var lcValues = <?php echo json_encode($myPHPArray); ?>;
</script>
[/sourcecode]
So much simpler! PHP4 has almost disappeared so there’s no reason not to use json_encode. I’d recommend that you stop reading now and just go with that.
If you use PHP to create web pages, there may be times when you need to create a JavaScript array dynamically from a PHP array. This is not hard to do, but there is a trap you need to be careful of: dealing with arrays containing only a single element. Continue reading →