How to use str_shuffle() Function In PHP
The str_shuffle() function is an inbuilt function in PHP and is used to randomly shuffle all the characters of a string passed to the function as a parameter. When a number is passed, it treats the number as the string and shuffles it. This function does not make any change in the original string or the number passed to it as a parameter. Instead, it returns a new string which is one of the possible permutations of the string passed to it in the parameter.
Example:
<?php
// This function will return a random
// string of specified length
function random_strings($length_of_string)
{
// String of all alphanumeric character
$str_result = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
// Shuffle the $str_result and returns substring
// of specified length
return substr(str_shuffle($str_result),
0, $length_of_string);
}
// This function will generate
// Random string of length 10
echo random_strings(10);
echo "\n";
// This function will generate
// Random string of length 8
echo random_strings(8);
?>
Output
hnQVgxd4FE 6EsbCc53
How to generate a random, unique, alphanumeric string in PHP
There are many ways to generate a random, unique, alphanumeric string in PHP which are given below:
Table of Content
- Using str_shuffle() Function
- Using md5() Function
- Using sha1() Function
- Using random_bytes() Function
- Using random_int() in a Custom Function