4

I am trying to assign a PHP array into a javascript variable like this:

var jsArray = <?php echo $phpArray; ?>;

But it doesn't work.
What am I doing wrong?

Ash
  • 1,289
  • 3
  • 17
  • 24
  • possible duplicate of [PHP to Javascript Array (Kind of)](http://stackoverflow.com/questions/1968977/php-to-javascript-array-kind-of) - There are even more duplicates of your question. Please use the search first and see as well the Related column on the right. – hakre Nov 17 '11 at 13:23

2 Answers2

14

You should try to use JSON

var jsArray = <?php echo json_encode($phpArray); ?>;

accessible then via

jsArray.someKey

demo

genesis
  • 50,477
  • 20
  • 96
  • 125
3

you can serialize array in php using json_encode and use it inside JS

http://php.net/manual/en/function.json-encode.php

<?php
$series = array("name"=>"N51",
                "data"=>array(1024,
                              array("y"=>2048,
                                    "events"=>array("mouseOver"=>'function(){$reporting.html(\'description of value\');}')
                                   ),
                              4096)
               );
json_encode($series);
?>

The above code outputs:

{"name":"N51","data":[1024,{"y":2048,"events":{"mouseOver":"function(){$reporting.html('description of value');}"}},4096]}
ahm_selim
  • 141
  • 2
  • 6