str_shuffle
str_shuffle($string)
Returns a string with the same characters in random order. Useful for games, anagrams and sample data. It is not suitable for passwords, tokens and discount codes, because its randomness is not secure.
Parameters
- $string – the text whose characters are to be shuffled.
Examples
$shuffled = str_shuffle("abcdef");
// the length and the characters stay, only the order changes
echo strlen($shuffled); // 6
echo count_chars($shuffled, 3); // abcdef
// eight random characters from your own set – each can appear at most once
$code = substr(str_shuffle("ABCDEFGHJKLMNPQRSTUVWXYZ23456789"), 0, 8);
echo count(array_unique(str_split($code))); // 8
// a secure random code – the characters are picked with random_int
$chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
$password = "";
for ($i = 0; $i < 12; $i++) {
$password .= $chars[random_int(0, strlen($chars) - 1)];
}
echo strlen($password); // 12
// a secure token (32 hexadecimal characters)
echo strlen(bin2hex(random_bytes(16))); // 32
// UTF-8 text is shuffled by characters
$letters = mb_str_split("résumé");
shuffle($letters);
echo mb_strlen(implode("", $letters)); // 6
Things to watch out for
- It is not cryptographically secure. It uses the same generator as mt_rand() and its output can be predicted. Create passwords, password reset tokens and discount codes with random_int() or random_bytes().
- The characters are only rearranged, none repeats more times than in the original text. A code cut from a shuffled set therefore has fewer possible combinations than a code made of randomly picked characters.
- It shuffles bytes. It breaks UTF-8 text with accents, use mb_str_split() and shuffle() as in the example.
- Arrays are shuffled by shuffle(), but it changes the passed array directly and does not return it.
- Since PHP 8.2 there is the Random\Randomizer class with the shuffleBytes() method, which can also shuffle with a secure generator.
Related functions:
str_split()
strrev()
str_repeat()
shuffle()