Reputation: 167
<?php
$array = array("first elem", "second elem");
?>
<html>
<head>
</head>
<body>
<script>
var js_array = '<?php echo json_encode($array); ?>';
for (var i = 0; i < js_array.length; i++)
{
document.write(js_array[i]);
document.write("<br>");
}
</script>
</body>
I have PHP array with two elements, when I converting this array to javascript array with json_encode()
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?
Upvotes: 1
Views: 91
Reputation: 2253
Replace you code with the following code..
<?php
$array = array("first elem", "second elem");
?>
<html>
<head>
</head>
<body>
<script>
var js_array = <?php echo json_encode($array); ?>;
for (var i = 0; i < js_array.length; i++)
{
document.write(js_array[i]);
document.write("<br>");
}
</script>
</body>
I hope its help you.....
Upvotes: 1
Reputation: 455
The problem is that you have enclosed the json_encode in colons so you are converting it to a string. The javascript it produces is like this:
var js_array = '["first elem","second elem"]';
Here js_array
is an string but you want an array. What you have to do is to produce the json directly as it will yield an array:
var js_array = <?php echo json_encode($array); ?>;
Upvotes: 1
Reputation: 5397
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); ?>;
Upvotes: 1