Backend Development 4 min read

Understanding PHP mt_rand and Five Ways to Generate Random Numbers

This article explains how PHP's mt_rand function works, its deterministic nature when the seed and PHP version are identical, and demonstrates five distinct code techniques—including range‑shuffle, unique random loops, mt_rand with array filtering, array slicing, and microtime‑seeded shuffling—to produce pseudo‑random sequences.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Understanding PHP mt_rand and Five Ways to Generate Random Numbers

PHP's mt_rand function generates pseudo‑random numbers whose sequence can be predicted if the seed (an unsigned int from 0 to 4294967295) and the PHP version are known.

When the same seed and PHP implementation are used, the generated numbers are identical, allowing an attacker to reproduce the sequence.

Method 1: range and shuffle

<?php
$arr = range(1, 10);
shuffle($arr);
foreach ($arr as $value) {
    echo $value . " ";
}
// Example output: 1 8 4 2 3 10 5 7 9 6
?>

Method 2: while loop with rand and array_unique

<?php
$arr = array();
while (count($arr) < 10) {
    $arr[] = rand(1, 10);
    $arr = array_unique($arr);
}
echo implode(" ", $arr);
// Example output: 4 8 6 9 3 1 10 5 2 7
?>

Method 3: using mt_rand with array filtering

<?php
$arr = array();
while (count($arr) < 10) {
    $arr[] = mt_rand(1, 10);
    $arr = array_flip(array_flip($arr)); // remove duplicates
}
foreach ($arr as $value) {
    echo $value . " ";
}
// Example output: 6 4 3 9 5 10 1 2 8 7
?>

Method 4: range, shuffle, and array_slice

<?php
$numbers = range(1, 100);
shuffle($numbers);
$no = 6;
$result = array_slice($numbers, 0, $no);
for ($i = 0; $i < $no; $i++) {
    echo $result[$i] . "
";
}
print_r($result);
// Example result: Array ( [0] => 62 [1] => 53 [2] => 93 [3] => 5 [4] => 16 [5] => 98 )
?>

Method 5: microtime seed with shuffle

<?php
$numbers = range(1, 20);
srand((float)microtime() * 1000000);
shuffle($numbers);
foreach ($numbers as $val) {
    echo $val . " ";
}
// Example output: 20 13 11 2 3 1 14 5 8 6 7 17 10 9 19 15 18 16 4 12
?>

By understanding the deterministic behavior of mt_rand and applying these code patterns, developers can generate random‑looking sequences for testing, games, or simple shuffling tasks while being aware of their predictability.

backendProgrammingphpRandom Number Generationmt_rand
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.