I have tried to implement PHP array into JavaScript but the problem is that it is not converting properly.
For example if PHP array $new_array has a value of a,q,s,t,u it is assigning to all the indexes of JavaScript array for example:
js_array[0]=a,q,s,t,u;
js_array[1]=a,q,s,t,u;
js_array[2]=a,q,s,t,u;
js_array[3]=a,q,s,t,u;
js_array[4]=a,q,s,t,u;
js_array[5]=a,q,s,t,u;
This is my PHP code:
$new_array = array(); // create a new array
$sql=mysql_query("SELECT * FROM animate ORDER BY RAND() LIMIT 5") or die("query Field");
while($row=mysql_fetch_array($sql)){
$new_array[] = $row['code'];
}
js code
var array =[<?php echo json_encode($new_array);?>];
alert(array[0]);
for(var i=0; i <=9 ; i++)
{
array[i]=[<?php echo json_encode($new_array);?>];
}
I want to assign values like:
array[0]=a;
array[1]=q;
array[2]=s;
array[3]=t;
array[4]=u;
I want to do in this pattern but it is not working.
cweiske
31.4k15 gold badges150 silver badges206 bronze badges
2 Answers 2
You could "implode" it or you could use JSON.
Implode Method
var array = [<?php echo implode($array, ","); ?>];
JSON Method
var array = <?php echo json_encode($array); ?>;
answered Apr 21, 2016 at 18:14
Dustin Poissant
3,5362 gold badges23 silver badges34 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Just iterate the php array inside the js array braces.
var array =[<?php foreach ($newArray as $value) echo "'" . $value . "',"; ?>];
You might have to put an additional line to clip the last ,
answered Apr 21, 2016 at 18:08
Charlie
24k12 gold badges65 silver badges97 bronze badges
Comments
default
$row['code']???[<?php encode ?>]is creating an array with your encoded array in it, which you then store in ANOTHER array. all you need isvar arr = <?php echo json_encode($your_array); ?>;