Open In App

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:
 

<?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
<?php

// This function will return a random
// string of specified length
function random_strings($length_of_string) {
    
    // md5 the timestamps and returns substring
    // of specified length
    return substr(md5(time()), 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
12945f0845
12945f08
<?php

  // This function will return 
  // A random string of specified length
  function random_strings($length_of_string) {
      
   
    // sha1 the timestamps and returns substring
    // of specified length
    return substr(sha1(time()), 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
643f60c52d
643f60c5
<?php

// This function will return
// A random string of specified length
function random_strings($length_of_string) {

    // random_bytes returns number of bytes
    // bin2hex converts them into hexadecimal format
    return substr(bin2hex(random_bytes($length_of_string)), 
                                      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
64713970f3
67b575a3


 Time complexity: O(length_of_string).

Space complexity: O(length_of_string).

Article Tags :