Here is the php array i am using. I am trying to convert each entry into a string and pass it to the javascript variable, but when i use the following code I only get the first letter of each word in the php array.
<?php
$terms = array('cat', 'dog', 'bird');
$rand_keys = array_rand($terms);
?>
Javascript variable with php array data
var searchterms = <?php echo json_encode($terms[$rand_keys]); ?>;
-
you want to create a js variable for each element of php array or any one js variable for random php array element.Gaurav– Gaurav2011年02月08日 19:08:16 +00:00Commented Feb 8, 2011 at 19:08
2 Answers 2
use shuffle($terms); then echo json_encode( $terms );
3 Comments
The following code just take a random element from the php array and not the whole array:
var searchterms = <?php echo json_encode($terms[$rand_keys]); ?>;
Use the following code to get all the elemenets:
var searchterms = <?php foreach ($terms as $t){echo json_encode($t);} ?>