Blog
How to Generate a Random Number in PHP
To generate a random integer in PHP, call random_int($min, $max). For example, random_int(1, 100) returns an integer from 1 through 100, including both endpoints. Use a supported PHP version and validate any range supplied by a user.
This guide covers random ranges, fixed-digit numbers, leading zeros, repeated results, and the differences between common PHP random functions. Try the interactive preview, or download the complete PHP form to run it locally.
Generate a PHP random number in one line
<?php
echo random_int(1, 100); // Possible result: 42
The result is an integer, and a later call can return the same value. PHP’s random_int() reference describes a uniformly selected value in a closed interval. It uses a cryptographically secure source; that does not make a short number a complete authentication system.
PHP random number examples at a glance
| Goal | PHP expression | Possible values |
|---|---|---|
| One decimal digit | random_int(0, 9) |
0–9 |
| Dice value | random_int(1, 6) |
1–6 |
| Two-digit positive integer | random_int(10, 99) |
10–99 |
| Five-digit positive integer | random_int(10000, 99999) |
10000–99999 |
| Six-digit positive integer | random_int(100000, 999999) |
100000–999999 |
| Negative to positive | random_int(-25, 25) |
−25–25, including zero |
These are integer ranges, so they do not preserve leading zeros. Choose string formatting when you need a fixed-width display.
Live demo: choose a range and generate numbers
This page runs a browser preview with Web Crypto. It demonstrates the same range behavior as the downloadable PHP form, but does not execute PHP in your browser or call a remote generator.
Random integer generator
Explore inclusive ranges in your browser. This preview uses Web Crypto, while the downloadable PHP form uses random_int() on your server.
Demo bounds: −1,000,000,000 to 1,000,000,000; count: 1–20. Use whole numbers without leading zeros. Repeats are allowed.
Ready. Choose a range and generate numbers.
Equivalent PHP loop:
for ($i = 0; $i < 5; $i++) {
echo random_int(1, 100) . PHP_EOL;
}
This public demo is for learning. It does not create or store authentication codes.
Enable JavaScript for this preview, or run the downloadable PHP form, which works without JavaScript.
random_int(), rand(), or mt_rand(): which should you use?
| Function | What it provides | Practical use |
|---|---|---|
random_int() |
Cryptographically secure integer in a supplied range | A convenient choice for simple random integer generation |
rand() |
Legacy pseudorandom integer API; uses the same generator as mt_rand() in modern PHP |
Understanding older examples; avoid for unguessable values |
mt_rand() |
Mersenne Twister pseudorandom integers | Existing non-security code; predictable when its state is known |
random_bytes() |
Cryptographically secure random bytes | Byte-based tokens, encoded for text output |
The PHP manuals for rand() and mt_rand() caution against using them where values need to be unguessable. Their documentation also points new code toward Random\Randomizer; random_int() remains a convenient API for a simple secure integer draw.
Generate several random integers in PHP
Call the function once per result and append each value to an array. The following example returns five draws. It does not promise five distinct values.
$numbers = [];
for ($i = 0; $i < 5; $i++) {
$numbers[] = random_int(1, 100);
}
echo implode(', ', $numbers);
If you need unique values, design a sampling-without-replacement step and reject a requested count larger than the available range. If you need a unique database identifier, enforce uniqueness in storage and handle collisions. Randomness and uniqueness are separate properties.
Display a random number with leading zeros
A six-character numeric string can begin with zero; a six-digit positive integer cannot. Format an integer from zero through 999999 as a padded string:
$displayCode = str_pad((string) random_int(0, 999999), 6, '0', STR_PAD_LEFT);
// Example display: "004217". Keep it as a string to retain the zeros.
This is a formatting example. A real verification flow also needs server-side checks, expiry, attempt limits, and one-time use. The public demo does not implement or store verification codes.
Validate range inputs and handle generation errors
Do not cast arbitrary request text and assume it is valid. Decide which integer notation and bounds your form accepts, validate the strings, then convert them. The project limits both endpoints to −1,000,000,000 through 1,000,000,000 and generates at most 20 results per request. Those are tutorial limits, not PHP's full integer range.
Reject a minimum greater than the maximum; equal endpoints are valid. Catch failures and show an error instead of silently switching to a weaker generator.
try {
// Validate request strings before assigning these integer bounds.
$minimum = 1;
$maximum = 100;
echo random_int($minimum, $maximum);
} catch (Throwable $error) {
http_response_code(503);
echo 'Random generation is unavailable. Please try again later.';
}
The downloadable random.php separates input validation from generation, and the form returns an input error for invalid parameters. A larger application can handle argument errors and random-source failures separately.
Run the downloadable PHP random number demo
Extract the ZIP and open a terminal in php-random-number-demo. With a supported PHP 8.x installation, run:
php -S 127.0.0.1:8080
Visit http://127.0.0.1:8080/index.php. Enter a range and count, then select Generate with PHP. The form works without JavaScript. The built-in server is for local development; stop it with Ctrl+C when finished.
php-random-number-demo/
├── index.php # PHP form and escaped output
├── random.php # Input validation and random_int() calls
├── preview.html # Browser-only generator
├── preview.js
├── style.css
└── README.md
Open preview.html for the standalone browser version. It uses crypto.getRandomValues() with rejection sampling, discarding the incomplete tail before mapping values into your range. This avoids adding modulo bias. It uses no Math.random() fallback and clears old results whenever inputs change.
Common problems and fixes
| Problem | Fix |
|---|---|
| The same number appears twice | Repeats are expected in independent draws. Add separate uniqueness rules if required. |
| A leading zero disappears | Keep the formatted value as a string. |
| The PHP source appears as text | Use a PHP server and a .php file; opening a file directly does not execute PHP. |
| The minimum is larger than the maximum | Correct the input order before generating. |
| A decimal or exponent is rejected by the demo | Use ordinary whole-number notation, such as -25 or 100. |
| Copy does not work in the browser | Use HTTPS/localhost when supported, or select and copy the displayed results manually. |
Frequently asked questions
Are the minimum and maximum included?
Yes. For example, the dice range can return both 1 and 6.
Can PHP generate negative random numbers?
Yes. Supply ordered integer bounds such as −25 and 25.
Does random_int() always return a different number?
No. Calls can repeat values. It does not track previously generated results.
Can I seed random_int() for repeatable tests?
No seed parameter is exposed. Test range and validation behavior without expecting a particular draw, or inject a deterministic test generator into your own application design.
What should I use for a random token?
For a byte-based token, use random_bytes() and a suitable text encoding. For example, bin2hex(random_bytes(16)) creates a 32-character hexadecimal representation of 16 random bytes. PHP's random_bytes() documentation explains why encoding is useful for displaying binary output.
Does the live demo execute PHP?
No. It runs locally in the browser. The ZIP includes a real PHP form so you can test server-side generation yourself.
Download and try the complete example
Start with a small inclusive range, test equal endpoints and negative values, and check invalid inputs. The download includes the PHP generator, browser preview, styling, and setup notes.