Re: multiple random items

From: Date: Wed, 18 Jul 2007 00:02:48 +0000
Subject: Re: multiple random items
References: 1 2 3  Groups: php.general 
Request: Send a blank email to php-general+get-259060@lists.php.net to get a copy of this message
On Mon, July 16, 2007 9:40 am, chris@aquanuke.com 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?

« previous php.general (#259060) next »