LostCore
12/22/2014 - 10:01 AM

Functions to generate a random string.

Functions to generate a random string.

<?php

/**
 * Generate a random string
 * @param int $n the number of characters 
 */
function randomStr( $n = 10 ) {
		$characters = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
		$string     = '';
		
		for ( $i = 0; $i < $n; $i ++ ) {
			$string .= $characters[ rand( 0, strlen( $characters ) - 1 ) ];
		}

		return $string;
}

//USAGE:
$string = randomStr(); //10 characters-long string
$string = randomStr(5); //5 characters-long string
/**
 * Generate a random string
 * @param n the number of characters 
 * @returns {string}
 */
function randomStr(n){
  if(typeof(n)==='undefined') n = 10;
  
  var text = "";
  var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

  for( var i=0; i < n; i++ ) {
      text += possible.charAt(Math.floor(Math.random() * possible.length));
  }
  return text;
}

//USAGE:
var string = randomStr(); //10 characters-long string
var string = randomStr(5); //5 characters-long string