Javascript – Double dimensional array value from PHP


I have a PHP file that is going to write a two-dimensional array in JavaScript:

    print "<script language='javascript'>";
    print " extra[0][0] = new Array(1,'Bob',12);";
    print " extra[0][1] = new Array(2,'Alice',18);";
    // Need to assign the extra[1][0], extra[1][1] and so on.
    print "</script>";


  var extra =  new Array();

How do I assign the two-dimensional array from PHP to a JavaScript variable?

Best Solution

json_encode is your friend: json_encode in the PHP manual

<script type="text/javascript">
  var jsArray = <?= json_encode($my_array) ?>;