PHP generates a random string includes letters

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

PHP generates a random string includes letters, there are two kinds of methods:

The first: the use of string manipulation functions

<?php
	/**
	 *@blog <www.phpddt.com>
	 */
	function createRandomStr($length){
		$str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';//62 characters
		$strlen = 62;
		while($length > $strlen){
			$str .= $str;
			$strlen += 62;
		}
		$str = str_shuffle($str);
		return substr($str,0,$length);
	}
	echo createRandomStr(10);

  

Second: the use of switching array and the character of the thought:

<?php
	/**
	 *@blog <www.phpddt.com>
	 */
	function createRandomStr($length){
		$str = array_merge(range(0,9),range('a','z'),range('A','Z'));
		shuffle($str);
		$str = implode('',array_slice($str,0,$length));
		return $str;
	}
	echo createRandomStr(10);

  

After 1000 cycles of testing, the first efficiency is high (the first calculation one thousand times about 0.02, second kinds of calculation one thousand times about 0.06s)!

Welcome to reprint! The original address:    , reproduced please specify the address, thank you!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Conrad at October 23, 2013 - 11:17 PM