PHP random number examples (rand function)

PHP random number FAQ: Can you show an example of the PHP random function?

Sure. To create a random number in PHP, just use a line of code like this:

$r = rand(1,10);

That will generate a random number from 1 to 10.

Real-world PHP random number example

Next, here's a snippet of PHP code that shows how to create a random number in PHP in some real-world code:


// a drupal php block example
// alvin alexander,

// first, here are the three snippets of HTML that I want to display in 
// my upper-left corner block

// (1) html for "subscribe to newletter"
$newsletter = <<< NEWSLETTER
<p class="rtecenter"><a
  target="_blank" border="0" href=""><img
  title="subscribe to our newsletter" alt="subscribe to our newsletter"
  src="/sites/default/files/users/user3/devdaily-news-96x77.png" /><br />
subscribe to our<br />
monthly newsletter</a></p>

// (2) html for "rss feed html"
$dd_rss_feed = <<< DD_RSS
<!-- RSS -->
<p class="rtecenter"><a
   href="/rss.xml"><img alt="Subscribe to our RSS feed"
   title="Subscribe to our RSS feed" src="/images/feed-icon-64x64-ds.png" /></a>
   <br />rss feed</p>

// (3) html for "write for devdaily html"
$dd_write = <<< WRITE_FOR_DD
<!-- WRITE -->
<p class="rtecenter"><br />
<a alt="Write for devdaily" title="Write for devdaily"
   href="/news/2010/06/03/devdaily-open-to-writers"><img alt=""
   src="/images/write/article-48.png" /><br />write for devdaily </a></p>
<p> </p>

// get a random number that varies from "1" to the number of 
// html content blocks you want to rotate
$r = rand(1,3);

// now emit the output based on the random number
if ($r == 1)
  echo $newsletter;
elseif ($r == 2)
  echo $dd_rss_feed;
  echo $dd_write;


I've made the PHP rand function call bold in that source code so you can see it more easily. As you can see, creating a random number in PHP is very simple. Just specify the lowest possible number and the highest possible number, and you're in business.

“Treat every moment as your last.
It is not preparation for something else.”
~ Shunryu Suzuki