3

I have a PHP array I want to use in my JavaScript code. I'd rather not do something like <?PHP $array['array2name'][0]?> for all of the elements in it as it's number is unknown. I was going to do a while loop to write in some of the data into elements but I cannot seem to find an easy way to do this currently.

How do I pass a 2d array from PHP to JavaScript in the easiest way possible?

Wesley Murch
  • 101,186
  • 37
  • 194
  • 228
133794m3r
  • 5,028
  • 3
  • 24
  • 37
  • 2
    Lots of duplicates I can see in the right column. E.g. http://stackoverflow.com/questions/2421875/write-to-javascript-array-within-php-loop (addresses the same issue) – Felix Kling May 12 '10 at 10:03
  • possible duplicate of [Best way to transfer an array between PHP and Javascript](http://stackoverflow.com/questions/393479/best-way-to-transfer-an-array-between-php-and-javascript) – Wesley Murch Apr 19 '12 at 02:06

2 Answers2

12

As a JSON Object using the json_encode function. You can then read this with Javascript easily as it is a native javascript object. http://php.net/manual/en/function.json-encode.php

json_encode($array);

JSON is easily parsable in JQuery, but for pure JavaScript see here:

http://www.json.org/js.html

Gazler
  • 83,029
  • 18
  • 279
  • 245
  • Problem with this is you lost the order of your array during the parsing from string to JSON object on javascript side. for example. array with key as 0 0.5 1 will be altered to 0 1 0.5 by javascript. This behavior varies by browser. – Gäng Tian Jun 05 '12 at 23:27
0

Lazy method:

<script>
var arr = [];

<?php
    $phparray = array(array(1, 2, 3), array(4, 5, 6));

    foreach ($phparray as $i) {
        echo 'arr.push([' . implode(', ', $i) . ']);';
    }
?>

</script>

This isn't the "best" method, but hey it works.

Alex
  • 285
  • 2
  • 8