Given a size N and the task is to generate a random string of size N.
Examples:
Input: 5 Output: eR3Ds Input: 10 Output: MPRCyBgdcn
Method: Create a domain string which contains small letters, capital letters and the digits (0 to 9). Then generate a random number and pick the character present at that random index and append that character into the answer string.
Below is the program to generate random string using above method:
<?php // PHP function to print a // random string of length n function RandomStringGenerator($n) { // Variable which store final string $generated_string = ""; // Create a string with the help of // small letters, capital letters and // digits. $domain = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; // Find the length of created string $len = strlen($domain); // Loop to create random string for ($i = 0; $i < $n; $i++) { // Generate a random index to pick // characters $index = rand(0, $len - 1); // Concatenating the character // in resultant string $generated_string = $generated_string . $domain[$index]; } // Return the random generated string return $generated_string; } // Driver code to test above function $n = 5; echo "Random String of length " . $n . " = " . RandomStringGenerator($n); ?> |
chevron_right
filter_none
Output:
Random String of length 5 = EEEto
Recommended Posts:
- PHP program to Generate the random number in the given range (min, max)
- How to generate a random, unique, alphanumeric string in PHP
- Generate random alpha-numeric string in JavaScript
- How to generate a random boolean using JavaScript ?
- How to Generate a Random Password using JavaScript ?
- How to generate random number in given range using JavaScript?
- Generating Random String Using PHP
- JavaScript | Program to generate one-time password (OTP)
- PHP | Program to check a string is a rotation of another string
- Golang Program that uses String Switch
- Python program to create a dictionary from a string
- PHP program to find the length of the last word in string
- Program to replace every space in a string with hyphen
- p5.js | random() Function
- How to get random value out of an array in PHP?
- JavaScript | Random
- Generate PDF in ElectronJS
- Underscore.js _.random() Function
- How to Generate Captcha Image in PHP ?
- How to generate an XML file dynamically using PHP?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : ManasChhabra2

