0

I have an array like this in PHP:

$array[] = 'bob';
$array[] = 'chris';
$array[] = 'sam';

How would I turn it into this, in JavaScript:

var array = [bob, chris, sam];

I have tried this code but it just returns var array = [Array];:

<script>
var array = [<?php echo $array; ?>];
</script>
bob jomes
  • 271
  • 1
  • 4
  • 13

1 Answers1

3

You can use json.

<script type="text/javascript">
var data = <?php echo json_encode($array); ?>;
</script>

And then you can use it in javascript like this:

var obj = JSON.parse(data)