PHP: Random sequence function

Here is a function I have created which is used to generate a sequence of random numbers, letters and symbols. I currently use it on a number of projects including which is a simple password generator.

How to use

$sequence = random_sequence(12); // Will generate a random sequence 12 characters in length


function random_sequence($size){
	//Sets up variable to store sequence
	$sequence = "";
	//Array full of the letters, numbers or symbols we want in are generated sequence
	$seq_possibilities = array(
		"A", "B", "C", "D", "E", "F", "G", "H",
		"I", "J", "K", "L", "M", "N", "O", "P",
		"Q", "R", "S", "T", "U", "V", "W", "X",
		"Y", "Z", "a", "b", "c", "d", "e", "f",
		"g", "h", "i", "j", "k", "l", "m", "n",
		"o", "p", "q", "r", "s", "t", "u", "v",
		"w", "x", "y", "z", "0", "1", "2", "3",
		"4", "5", "6", "7", "8", "9"
	//Performs a loop to generate our sequence
		//Generates a random number between 0 and the size of the array above, we then
		//get the requred value from the array and place it onto the end of our already
		//generated sequence
		$sequence .= $seq_possibilities[rand(0, sizeof($seq_possibilities) - 1)];
	//We keep looping until our sequence is how long we wanted it
	}while(strlen($sequence) < $size);
	//Returns the sequence
	return $sequence;

How it works

The function can be adjusted to allow different characters and symbols to be generated in a sequence, there is a variable (array) called $seq_possibilities, you simply adjust the data which is first added into this array to the characters and symbols you want to be used in your sequences.

The function works by looping the specified number of times (when you call the function you pass the size of the sequence you require), on every loop it will use the rand() function and generate a number between zero and the size of $seq_possibilities array, the array data will then be pulled out of the array and placed onto the end of the $sequence variable. After it has loop enough times we will return the generated sequence.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.