PHP Random Numbers & letters

This is the simple function of generating a random numbers in php.

<?php
function Random($length=5){
	$key = '';
	$pattern = "12345678901234567890123456789012345678901234567890";
	for($i=0;$i<$length;$i++){
		$key .= $pattern{rand(0,35)};
	  	}
	return $key;
}

echo Random(8);

?>

Sample Output:

function Random($length=5)
{
$key = '';
$pattern = '12345678901234567890123456789012345678901234567890';
for($i=0;$i<$length;$i++){
$key .= $pattern{rand(0,35)};
}
return $key;
}
echo '

';
echo Random(8);
echo '

';
?>

You can also add a different pattern like letters and combination of letters and numbers.


<?php
function Random2($length=5,$type=1){
		$key = '';
		switch($type){
			case 2:
				$pattern = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz";
				break;
			case 3:
				$pattern = "12345678901234567890123456789012345678901234567890";
				break;
			default:
				$pattern = "1234567890abcdefghijklmnopqrstuvwxyz";
				break;
		}
		for($i=0;$i<$length;$i++){
			$key .= $pattern{rand(0,35)};
		}
	   return $key;
}
echo strtoupper(Random2(6,1));
?>

Sample Output:

function Random2($length=5,$type=1){
$key = '';
switch($type){
case 2:
$pattern = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz";
break;
case 3:
$pattern = "12345678901234567890123456789012345678901234567890";
break;
default:
$pattern = "1234567890abcdefghijklmnopqrstuvwxyz";
break;
}
for($i=0;$i<$length;$i++){
$key .= $pattern{rand(0,35)};
}
return $key;
}

echo '

';
echo strtoupper(Random2(6,1));
echo '

';

?>

PG

Author: insic

Subscribe in my RSS Feed for more updates on Web Design and Development related articles. Follow me on twitter or drop a message to my inbox.

Related Post

Delicious

One Response to “PHP Random Numbers & letters”

  1. ur sample is good and consistent man. keep making more functions. great help for the new ones

Leave a Reply