Convert php array to javascript array

Updated: 28th March 2023
Tags: php javascript

To convert php array to javascript array use json_encode()

Simple plain array

<?php
$a = [1, 2 ,3];
$b = ['cat', 'dog', 'mouse'];
//const a = [1,2,3];
//const b = ["cat","dog","mouse"];
const a = <?=json_encode($a)?>;
const b = <?=json_encode($b)?>;

Associative array

<?php
$a = [["cat" => 1], ["dog" => 2, "mouse" => 3]];

$b = [
    "first" => ["cat" => 1],
    "second" => ["dog" => 2, "mouse" => 3],
];
//const a = [{"cat":1},{"dog":2,"mouse":3}];
//const b = {"first":{"cat":1},"second":{"dog":2,"mouse":3}};
const a = <?=json_encode($a)?>;
const b = <?=json_encode($b)?>;

Happy coding!