The str_shuffle function in PHP is often used to randomly disrupt the sequence of strings and generate various random permutations. It is very simple to use, such as:
<?php
$original = "abcdef";
$shuffled = str_shuffle($original);
echo $shuffled;
?>
Each time this code is executed, it returns a random permutation combination of the original string. However, in some application scenarios, we want the generated random combinations not to be repeated, such as generating verification codes, random passwords, lottery sequences, etc.
However, due to the random nature of str_shuffle , it is still possible to produce the same permutation each time you call, especially when the sample size is small or the number of calls is large, the probability of duplication increases significantly. So, how to avoid generating duplicate character combinations? Here are a few practical strategies.
The most intuitive method is to generate a new random string and store it in an array or collection. When generating a new string, check whether it already exists, and regenerate it if it exists.
<?php
$original = "abcdef";
$generated = [];
function generateUniqueShuffle($str, &$history) {
do {
$shuffled = str_shuffle($str);
} while (in_array($shuffled, $history));
$history[] = $shuffled;
return $shuffled;
}
// Example:generate10A unique random combination
for ($i = 0; $i < 10; $i++) {
echo generateUniqueShuffle($original, $generated) . "\n";
}
?>
This method is simple, but as the number of generations increases, the duplication checking will become slower and may eventually generate less than the desired number (limited combinations).
All permutations of strings are limited (strings of length n have n! permutations). You can first use a recursive algorithm to generate all permutations, store them, and then randomly extract and deduplicate them.
Example generates a fully-arranged core code:
<?php
function permute($str, $prefix = '') {
$result = [];
$len = strlen($str);
if ($len == 0) {
$result[] = $prefix;
} else {
for ($i = 0; $i < $len; $i++) {
$rem = substr($str, 0, $i) . substr($str, $i + 1);
$result = array_merge($result, permute($rem, $prefix . $str[$i]));
}
}
return $result;
}
$original = "abc";
$allPermutations = permute($original);
shuffle($allPermutations); // Random disruption order
foreach ($allPermutations as $perm) {
echo $perm . "\n";
}
?>
This method is suitable for short string lengths (usually less than 8), because the number of full permutations explodes (8! = 40320), which consumes a lot of memory and time.
If you need to avoid duplication across requests or for a long time, you can record the generated combination in the database or cache (such as Redis), and check whether it is duplicated after each generation, and then decide whether to return.
This method is very practical in multi-user environments or when generating large batches of random combinations, avoiding excessive memory usage and ensuring uniqueness.
Example pseudocode ideas:
<?php
// Connect to the database,Query if the current combination already exists
// If there is,则重新generate,直到generate唯一组合
// Insert the new combination into the database to save
?>
The specific implementation will depend on the database system and business needs you use.
If you just avoid simple repetition, you can also combine str_shuffle and random character replacement to increase random space. For example, after disruption, randomly replace several of the characters in the other allowed character sets.
This reduces the probability of repetition, but is not guaranteed to be absolutely unique.
Small-scale and simple scenarios : save the generated results with an array, and loop detection avoids duplication;
Medium-sized and short strings : pre-generated full permutations, randomly drawn;
Large-scale and persistent uniqueness : use databases or caches to deduplicate records;
Enhanced randomness : Combined with other random transformation methods, reduce the probability of repetition.
When choosing a strategy, you need to weigh the string length, number of generations, performance, and memory usage, and design a reasonable solution.