scriptygoddess

01 Apr, 2010

Showing multiple random quotes

Posted by: Jennifer In: PHP|Script snippet

Showing random quotes isn't anything new. When I needed to do something similar on a site recently, there were plenty of pre-written scripts to choose from. The trick however, was that I wanted to show more than one quote at a time (and of course I didn't want to show the same quote twice. That wasn't as easy to find. (I'm sure there's variations out there, but now I'll always have a place to find mine) ;)

First step is to load all the quotes you want into an array:

$quotes[] = "This is line 1";
$quotes[] = "This is line 2";
$quotes[] = "this is line 3";
$quotes[] = "This is another line";
$quotes[] = "This is yet another line";
$quotes[] = "Line 6";

Now get a handful of keys using array_rand:

$rand_keys = array_rand($quotes, 2);

We specified to get two random keys from the $quotes array – (You can grab more if you want, just change the "2")

Now that we have our random keys – you can either list them out one by one like this:

//show the first quote...
echo $quotes[$rand_keys[0]];
//show the second quote
echo $quotes[$rand_keys[1]];

Or you can loop through the keys like this:

foreach ($rand_keys as $value) {
echo $quotes[$value]."<br />";
}

That's all there is to it.

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

1 Response to "Showing multiple random quotes"

1 | John

July 9th, 2010 at 7:20 am

Avatar

I was trying to do exactly this… I was close but not as close as you :)

awesome!

Thanks!

Comment Form

Featured Sponsors


  • Curt: If anyone comes across this with similar issues I was able to sort out the pagination issues painlessly with easyCommentsPaginate from http://www.mush
  • Christopher: Yeah, it is indeed hard to do. And something remains elusive about why the pagination never worked. I tried everything I could find. Regardless, I
  • Jennifer: Hi Christopher, always hard to bug test stuff like that remotely. Sorry those didn't help. Glad you found a solution though :)

About


Advertisements