Unique Random Numbers in PHP
If you would like to show random numbers using PHP you can do this:
I needed this for generating unique lottery-style numbers for a contest page. The key here is the in_array check inside the while loop — it ensures no duplicates end up in the final array. Without that check, mt_rand can easily produce the same number twice.
Note that this approach gets slower as the array fills up, since each new number has to be checked against all existing ones. For small ranges like 1-100 it’s fine, but for larger sets you’d be better off using range() to create the full array and then shuffle() it — that’s O(n) instead of potentially much worse.
<?php
$min = 1;
$max = 100;
$total = 100;
$arrItems = array();
while ( count($arrItems) < $total ) {
$item = mt_rand($min,$max);
if (!in_array($item,$arrItems)) {
$arrItems[] = $item;
echo $item."<br />";
}
}