Random Numbers

Generate random integers with rand() and random_int().

Syntaxrand($min, $max);

PHP can generate random numbers:

  • rand(min, max) — a pseudo-random integer in a range.
  • random_int(min, max) — a cryptographically secure random integer.
  • mt_rand() — a faster pseudo-random generator.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Generate a secure random token for a password-reset link using random_int() and base64_encode().
  • Pick a random item from an array of promotional banner images to display on a homepage.
  • Simulate a dice roll in a board-game application using rand(1, 6).

More examples

rand for basic random integers

rand() generates a pseudo-random integer between the given min and max, suitable for non-security uses.

Example · php
<?php
$dice   = rand(1, 6);
$coin   = rand(0, 1) === 1 ? 'heads' : 'tails';

echo "Dice: $dice\n";
echo "Coin: $coin";

random_int for cryptographic use

random_int() and random_bytes() use a CSPRNG, making them safe for PINs, tokens, and security-sensitive values.

Example · php
<?php
$pin   = random_int(100000, 999999);
$token = bin2hex(random_bytes(16));

echo "PIN: $pin\n";
echo "Token: $token";

Shuffling and picking from arrays

shuffle() randomises an array in place; grabbing the first element after shuffling is a clean random-pick pattern.

Example · php
<?php
$banners = ['promo_a', 'promo_b', 'promo_c', 'promo_d'];
shuffle($banners);
$featured = $banners[0];

echo "Showing: $featured";

Discussion

  • Be the first to comment on this lesson.