Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating (pseudo)random alpha-numeric strings

Tags:

php

random

How can I generate a (pseudo)random alpha-numeric string, something like: 'd79jd8c' in PHP?

like image 863
UnkwnTech Avatar asked Sep 07 '08 04:09

UnkwnTech


People also ask

How do you generate random alphanumeric strings?

Method 1: Using Math. random() Here the function getAlphaNumericString(n) generates a random number of length a string. This number is an index of a Character and this Character is appended in temporary local variable sb. In the end sb is returned.

How do you generate random alphanumeric strings in C++?

Example 1: Using the rand() Function to Generate Random Alphabets in C++ The following C++ program generates a random string alphabet by using rand() function and srand() function. The rand() function generates the random alphabets in a string and srand() function is used to seed the rand() function.

How do you generate random unique alphanumeric strings in C#?

Initialize an empty string and name it as “randomString”. Choose the size of the string to be generated. Now using Next() method generate a random number and select the character at that index in the alphanumeric string. Append that character to randomString.


1 Answers

First make a string with all your possible characters:

 $characters = 'abcdefghijklmnopqrstuvwxyz0123456789'; 

You could also use range() to do this more quickly.

Then, in a loop, choose a random number and use it as the index to the $characters string to get a random character, and append it to your string:

 $string = '';  $max = strlen($characters) - 1;  for ($i = 0; $i < $random_string_length; $i++) {       $string .= $characters[mt_rand(0, $max)];  } 

$random_string_length is the length of the random string.

like image 191
Paige Ruten Avatar answered Oct 12 '22 02:10

Paige Ruten