PHP Random Number Generator
Random numbers in PHP: a random integer in any range, floats, picking and shuffling, and secure random values - with ready-to-paste code
How to generate a random number in PHP: random_int() is both easy and cryptographically secure, so it is the right default. Choose a range above for a ready-to-paste snippet.
Random Integer in a Range
random_int($min, $max) includes both ends and is cryptographically secure (PHP 7+). mt_rand is faster but predictable; rand() is an alias of it since PHP 7.1.
$n = random_int(1, 10); // 1..10, secure
$m = mt_rand(1, 10); // 1..10, not secure
Random Float
PHP 8.3 added Random\Randomizer::getFloat; before that, divide mt_rand() by mt_getrandmax().
$r = new \Random\Randomizer();
$f = $r->getFloat(1.5, 4.5); // PHP 8.3+
$g = mt_rand() / mt_getrandmax(); // 0.0 <= g <= 1.0
Random Element and Shuffle
array_rand and shuffle use the non-secure generator; Random\Randomizer (PHP 8.2+) defaults to the secure engine.
$items = ["red", "green", "blue"];
$pick = $items[array_rand($items)]; // not secure
$securePick = $items[random_int(0, count($items) - 1)]; // secure
shuffle($items); // not secure
$shuffled = (new \Random\Randomizer())->shuffleArray($items); // secure, PHP 8.2+
Secure Tokens and Strings
For tokens, reset links and API keys, generate random bytes and encode them.
$token = bin2hex(random_bytes(16)); // 32 hex characters
Common Mistakes
uniqid() is based on the clock, not random - never use it for tokens. Neither rand() nor mt_rand() is safe for passwords or tokens; random_int and random_bytes are.
Frequently Asked Questions
How do I generate a random number between 1 and 10 in PHP? ▶
What is the difference between rand, mt_rand and random_int? ▶
How do I generate a random string in PHP? ▶
Is random_int inclusive? ▶
[ HOW TO CITE THIS PAGE ]
Generate-Random.org. (2026). PHP Random Number Generator. Retrieved from https://generate-random.org/random-number-php
PHP Random Number Generator - Generate-Random.org (https://generate-random.org/random-number-php)