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.
<?php
echo random_int(1, 6); // like rolling a die
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.
<?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
<?php
$random = mt_rand() / mt_getrandmax(); // between 0 and 1
echo round($random, 3);
Pick a random item from an array
<?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
<?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.
<?php
mt_srand(42);
$first = mt_rand(1, 100);
mt_srand(42);
$second = mt_rand(1, 100);
var_dump($first === $second);
bool(true)
Random strings for tokens
Use random_bytes() and turn it into text with bin2hex().
<?php
$token = bin2hex(random_bytes(16));
echo strlen($token);
32
The token has 16 random bytes, which is 32 hex characters. Use this for password reset links, CSRF tokens and session IDs.
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.