Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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]); ?>;
share|improve this question
you want to create a js variable for each element of php array or any one js variable for random php array element. – Gaurav Feb 8 '11 at 19:08

2 Answers

use shuffle($terms); then echo json_encode( $terms );

share|improve this answer
this works great but when what if i wanted to dd many more terms to the php array. i looked at the source and it displays all the terms like this var searchterms = ["slamjam","kenny","opp","heel","dog","bird","lol","flip","aaa","juu","sam","ste‌​rn","ben","upndon","cat"]; is there any way to make it display one term at a time? – Dan Feb 8 '11 at 19:20
@Dan are you converting searchterms to a json object? – Andrew Jackman Feb 8 '11 at 19:29
no, should I do that? – Dan Feb 8 '11 at 19:35
@Dan yup :) since it is a trusted source you can use eval(), then you can navigate the json object similar to an array (searchterms[0] will show the first value) – Andrew Jackman Feb 8 '11 at 19:37

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);} ?>

share|improve this answer
thank you but i need the terms to echo back randomly – Dan Feb 8 '11 at 19:22

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.