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

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

2 Comments

I just noticed this puts " around the names. How do I stop this?
That is JSON format. When you parse it to javascript object " around property names will disappear.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.