I have an array which have some values stored in it but I want to transfer the elements of that array into javascript array for further processing. How can I do so?
Asked
Active
Viewed 30 times
1 Answers
2
You can encode your variable to json using json_encode($php_array)
.
Then on JavaScript side, parse it back using JSON.parse()
<script>
var foo = <?php echo json_encode($array); ?>;
</script>

Alexandre Tranchant
- 4,426
- 4
- 43
- 70
-
4No reason to parse it in JavaScript. JSON is already valid JavaScript. This just opens the door for injections. `let foo = = json_encode($array) ?>;` – Peter Apr 27 '19 at 12:06
-