Anthony Gorshenin Anthony Gorshenin - 7 months ago 45
JSON Question

converting with json_encode()

$array = array("first elem", "second elem");
var js_array = '<?php echo json_encode($array); ?>';

for (var i = 0; i < js_array.length; i++)

I have PHP array with two elements, when I converting this array to javascript array with
javascript divide my PHP array into set of chars, so in javascript array in a result i have a lot of elements. How to convert PHP array with two elements to javascript array with the same two elements?


You php function json_encode will give you a valid object, that's in fact what it means, JavaScript Object Notation.

So by using it as it is you will create an object in your JavaScript code. By enclosing it between apostrophes you are making it a string (who's value can be parsed as JSON).

So the simplest change would be to remove the apostrophes. So this line:

var js_array = '<?php echo json_encode($array); ?>';

Should become

var js_array = <?php echo json_encode($array); ?>;