Home · Examples · Select at Random

Select at Random

Every so often, when making web sites, it's useful to have some randomness so that the end users won't see the same old stuff over and over again. And this can be accomplished easily using PHP. Here's how.

First we'll create a variable called $x and assign it to the PHP rand() function, which, by itself, just generates a random number. Since we already have some idea as to how many random phrases (or images, etc.) we wish to display, we can specify two parameters, (numbers) stating where to start and where to stop.

For example, we wish to have 10 random phrases, we could use 0 - 9. (0 is included, so that's 10.)

$x = rand(0, 9);

And now we add the echo construct to display it on screen....

$x = rand(0, 9);
echo $x;

And the output of that code generates a random number.

That's wonderful, but we need add a bit more to it. We need to create a condition, using a switch() statement (also called a case block) which will then display our text based upon the selected number.

Remember the condition is $x, so based upon it's value, the displayed text changes.

$x = rand(0, 2); // three options

switch($x) {
  case 0:
  echo "its zero";
  break;
  case 1:
  echo "its one";
  break;
  case 2:
  echo "its two";
  break;
}

Now we have random text.

And there you have it; the simplest way to make randomness using PHP.

Additionally, in some cases too, we might need to randomly pull items out of an Array. If $b is our array, we can quite easily assign the array_rand() function to $x inorder to get our values, like this:

$b = array("25","50","75","100");
$x
= array_rand($b);
echo $b[$x];

Of course there are plenty of other ways to generate random values. If you'd like to share, please feel free to send them to me.

Jul 08, 2007

Comments

Rob Apr 04, 2007

Thanks. I was looking for that. Although it's unusual that there just isn't a clean PHP function to randomly select an arrays value instead of the key.

But this will work.
Rob

Write a comment

* = required field

:

:

:


5 + 2 =