Re: multiple random items

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Mon, July 16, 2007 9:40 am, chris@xxxxxxxxxxxx wrote:
> Hi I have this script which pulls 1 random item from a txt file.
> How would I modify it to pull 10 random items.

To forestall a rather lengthy discussion on what you mean by 10 random
items, I'm actually not going to answer that question.

I'm going to answer "10 unique items selected at random" instead. :-)

[I.e., I assume you don't want the same random quote to appear twice
in one list.]

> <?php
> $delim = "\n";
> $quotefile = "names.txt";
> $fp = fopen($quotefile, "r");
> $contents = fread($fp, filesize($quotefile));
> $quote_arr = explode($delim,$contents);
> fclose($fp);
> // generate random quote index

$uniques = array();
while (count($uniques) < 10){

> $quote_index = (mt_rand(1, sizeof($quote_arr)) - 1);

if (isset($uniques[$quote_index])) continue;
$uniques[$quote_index] = $quote_index;

> // get quote at $quote_index and return it
> $herequote = $quote_arr[$quote_index];
> echo "<li><a href='http://www.$herequote'>$herequote</a></li>";

}

> ?>

YMMV

-- 
Some people have a "gift" link here.
Know what I want?
I want you to buy a CD from some indie artist.
http://cdbaby.com/browse/from/lynch
Yeah, I get a buck. So?

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux