Assigning php array to javascript array

I am trying to assign a PHP array to a javascript variable as follows:

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

But that does not work.
What am I doing wrong?

+4
source share
2 answers

You should try using JSON

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

available through

 jsArray.someKey 

demo

+14
source

you can serialize an 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]}
+3
source

Source: https://habr.com/ru/post/1381694/


All Articles