Skip to content

PHP Tutorial Numbers and Math

Random Numbers

Lesson 75 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

PHP can generate random numbers. Which function you use depends on what the number is for.

random_int(): the one to remember

random_int($min, $max) returns a random integer between two values, both included.

index.php
PHP
<?php
echo random_int(1, 6); // like rolling a die
Output
OUTPUT
4

Your number will be different each run. random_int() is cryptographically secure, so use it for anything that matters: tokens, codes, passwords.

mt_rand() and rand()

mt_rand() and rand() also give random integers. They are fast, but not secure. They are fine for games, shuffling a playlist or picking a random greeting.

index.php
PHP
<?php
echo mt_rand(1, 100);
echo rand(1, 100); // today an alias of mt_rand()

Since PHP 7.1, rand() calls the same generator as mt_rand(), so there is no need to prefer one over the other.

A random float

index.php
PHP
<?php
$random = mt_rand() / mt_getrandmax(); // between 0 and 1
echo round($random, 3);

Pick a random item from an array

index.php
PHP
<?php
$colors = ["red", "green", "blue"];

echo $colors[array_rand($colors)];

array_rand() returns a random key, so use it to read the value.

Shuffle a list

index.php
PHP
<?php
$cards = [1, 2, 3, 4, 5];
shuffle($cards);

echo implode(", ", $cards);

Repeatable results with a seed

For tests and demos, you can make mt_rand() repeat the same numbers by setting a seed.

index.php
PHP
<?php
mt_srand(42);
$first = mt_rand(1, 100);

mt_srand(42);
$second = mt_rand(1, 100);

var_dump($first === $second);
Output
OUTPUT
bool(true)

Random strings for tokens

Use random_bytes() and turn it into text with bin2hex().

index.php
PHP
<?php
$token = bin2hex(random_bytes(16));

echo strlen($token);
Output
OUTPUT
32

The token has 16 random bytes, which is 32 hex characters. Use this for password reset links, CSRF tokens and session IDs.

dangerous
Never use rand() for security
rand() and mt_rand() can be predicted by an attacker who sees enough output. Use random_int() and random_bytes() for anything related to security.