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.

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!

Featured Sponsors

Genesis Framework for WordPress

Advertise Here


  • Scott: Just moved changed the site URL as WP's installed in a subfolder. Cookie clearance worked for me. Thanks!
  • Stephen Lareau: Hi great blog thanks. Just thought I would add that it helps to put target = like this:1-800-555-1212 and
  • Cord Blomquist: Jennifer, you may want to check out tp2wp.com, a new service my company just launched that converts TypePad and Movable Type export files into WordPre

About


Advertisements