Random Number Generator in PHP

How to generate and use random numbers for different purposes in PHP.


Edited: 2021-02-14 05:34

Random numbers, PHP

PHP comes with its own function for generating random numbers, so there is really not any reason to create your own algorithm.

Of course, when we talk about "random numbers", you should remember that there really is not such thing as a truly random number; in this context, "random" just means that we can not predict what the number is going to be, since we do not know the state of the algorithm used to generate the number. It is, of course, an irrelevant technical detail that most of us never have to think about.

Random numbers can be generated many different ways, some of which use external input as a "seed" value for the number. If you were to create a random number generator yourself, then you might use the current date, hour, or second as a seed value.

Now, it happens that PHP already has a function for generating random numbers, rand, which you can use, so there is no reason to create your own. Here is an example:

echo rand(1, 20); // Outputs a whole number E.g.: 1, 5, 20

Showing a random message

One thing that generating random numbers is useful for, is when you want to display a random message to the user; an easy way to do this is by having an indexed array containing the items you want to randomly choose from.

$items = [];

$items[] = 'Welcome to my website young one.';
$items[] = 'Today is a good day.';
$items[] = 'Fantastic entrance. Welcome. Have a look around.';
$items[] = 'Welcome. No funny business!';

$i = count($items);

$picked_item = rand(0, $i-1);

echo $items["$picked_item"];

Since an indexed array begins from "0", you will have to subtract "1" from the, $i, count variable.

It should be relatively easy for you to change this to instead show a random image; or, if you feel like it, you can also just read this tutorial: Show random image with PHP


  1. rand - php.net

Tell us what you think:

  1. How to use the AVIF image format in PHP; A1 or AVIF is a new image format that offers better compression than WebP, JPEG and PNG, and that already works in Google Chrome.
  2. How to create a router in PHP to handle different request types, paths, and request parameters.
  3. How much faster is C++ than PHP to increment and display a counter in a loop?
  4. Detecting the request method used to fetch a web page with PHP, routing, HTTP responses, and more.
  5. How to create a custom error handler for PHP that handles non-fetal errors.

More in: PHP Tutorials