How to use random_int() in a Custom Function In PHP
Using `random_int()` in a custom function generates a secure random alphanumeric string by selecting characters from a predefined set. It iterates to build a string of specified length, ensuring cryptographic security. Suitable for generating unique identifiers or secure tokens.
Example
<?php
// Function to generate a random string of specified length
function random_strings($length_of_string) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$characters_length = strlen($characters);
$random_string = '';
// Generate random characters until the string reaches desired length
for ($i = 0; $i < $length_of_string; $i++) {
$random_index = random_int(0, $characters_length - 1);
$random_string .= $characters[$random_index];
}
return $random_string;
}
// Generate and output random string of length 10
echo random_strings(10) . "\n";
// Generate and output random string of length 8
echo random_strings(8) . "\n";
?>
Output
asYSGGAKxe XxTNFXBN
Time complexity: O(length_of_string).
Space complexity: O(length_of_string).
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