Generating Random Numbers in PHP Using shuffle, array_unique, array_flip, and Custom Functions
This article demonstrates multiple PHP techniques for generating unique random numbers, including using shuffle on a range array, applying array_unique with a while loop, leveraging array_flip to remove duplicates, and creating a customizable randpw function with mt_rand, complete with code examples and output results.
This guide shows several ways to produce random numbers in PHP while ensuring uniqueness.
1. Using shuffle on a range array
<?php
$arr = range(1,10);
shuffle($arr);
foreach($arr as $value){
echo $value . " ";
}
?>Result: a shuffled sequence such as 10 1 4 3 7 5 8 9 2 6 .
2. Using array_unique with a while loop
<?php
$arr = array();
while(count($arr) < 10){
$arr[] = rand(1,10);
$arr = array_unique($arr);
}
echo implode(" ",$arr);
?>Result: a unique set of numbers like 9 8 2 5 7 3 6 4 10 1 .
3. Using array_flip to eliminate duplicates
<?php
$arr = array();
$count = 0;
$return = array();
while($count < 10){
$return[] = mt_rand(1,10);
$return = array_flip(array_flip($return));
$count = count($return);
}
foreach($return as $value){
echo $value . " ";
}
?>Result: another unique random sequence such as 10 9 2 1 6 8 3 7 5 4 .
4. Custom randpw function for flexible random strings
<?php
function randpw($len=8,$format='ALL'){
$is_abc = $is_numer = 0;
$password = '';
switch($format){
case 'ALL':
$chars = 'ABCDEQRSTUVWXYZabcijklmnopqrstuvwxyz0123456789';
break;
case 'CHAR':
$chars = 'ABCDE...9'; // trimmed for brevity
break;
case 'NUMBER':
$chars = '0123456789';
break;
default:
$chars = 'ABCDE...9';
}
mt_srand((double)microtime()*1000000*getmypid());
while(strlen($password) < $len){
$tmp = substr($chars, mt_rand()%strlen($chars), 1);
if(($is_numer<1 && is_numeric($tmp)) || $format=='CHAR') $is_numer = 1;
if(($is_abc<1 && preg_match('/[a-zA-Z]/',$tmp)) || $format=='NUMBER') $is_abc = 1;
$password .= $tmp;
}
return $password;
}
for($i=0;$i<10;$i++){
echo randpw(8,'NUMBER');
echo "
";
}
?>This function can generate numeric, alphabetic, or mixed passwords of a specified length.
5. Direct use of mt_rand
<?php
echo mt_rand(1,10);
?>Result: a single random integer between 1 and 10, e.g., 5 .
All examples include the actual output produced by each method, illustrating how to obtain non‑repeating random numbers in PHP.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.