1

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]); ?>;
asked Feb 8, 2011 at 18:54
1
  • you want to create a js variable for each element of php array or any one js variable for random php array element. Commented Feb 8, 2011 at 19:08

2 Answers 2

2

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

answered Feb 8, 2011 at 19:09
Sign up to request clarification or add additional context in comments.

3 Comments

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","stern","ben","upndon","cat"]; is there any way to make it display one term at a time?
@Dan are you converting searchterms to a json object?
@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)
1

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

answered Feb 8, 2011 at 19:07

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.