Forum Moderators: coopster

Message Too Old, No Replies

Random $var not working.

It stays the same everytime its echo'ed

         

sauce

12:32 am on Nov 7, 2005 (gmt 0)

10+ Year Member



I wrote a script to display a list of random different words, each on a seperate line, from text file but it seems everytime I call the $var its the same word...

Here is the script:

$wordlist = file("http://$HTTP_SERVER_VARS[HTTP_HOST]/wordlist.txt");
$num_rows = sizeof($wordlist);
$word = $wordlist[rand(0, $num_rows - 1)];

Now when I try to display 5 random words at different parts of my page they are randomized per page load but not indvidually.

Ex:
<?php echo $word;?>
<?php echo $word;?>
<?php echo $word;?>
<?php echo $word;?>
<?php echo $word;?>

Displays:

word23
word23
word23
word23
word23

what I'm tryin to do is have it display:

word11
word55
word8
word21
word14

willybfriendly

12:41 am on Nov 7, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



It looks like you are only assigning a value to $word one time. The script is doing exactly what you are asking it to.

A different approach would be to read the word list into an array, then use shuffle to randomize the array, and finally print out the first five elements of the array.

WBF

dreamcatcher

8:59 am on Nov 7, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Yes, willybfriendly is correct. $word will only ever have one value and you are simply echoing that value 5 times.

As you are using the file function you are already reading your data into an array, so do something like this:


$wordlist = file("http://$HTTP_SERVER_VARS[HTTP_HOST]/wordlist.txt");

shuffle($wordlist);

Ex:
<?php echo $wordlist[0];?>
<?php echo $wordlist[1];?>
<?php echo $wordlist[2];?>
<?php echo $wordlist[3];?>
<?php echo $wordlist[4];?>

dc