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?

1
  • possible duplicate of 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. Commented Nov 17, 2011 at 13:23

2 Answers 2

14

You should try to use JSON

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

accessible then via

jsArray.someKey

demo

Sign up to request clarification or add additional context in comments.

Comments

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]}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.