Function to Generate a PHP Random String of Numbers and Letters


Here’s a quick snippet of code that allows you to quickly generate a random string of letters and/or numbers based on the variables you feed into the function.

<?php
//Generate Random String
function generateCode($numchars=5,$digits=1,$letters=1)
{
$dig = "012345678923456789";
$abc = "ABCDEFGHJKLMNOPQRSTUVWXYZ";

if($letters == 1)
{
$str .= $abc;
}

if($digits == 1)
{
$str .= $dig;
}

for($i=0; $i < $numchars; $i++)
{
$randomized .= $str{rand() % strlen($str)};
}

return $randomized;
}
$code = generateCode('5','0','1');
echo $code;
?>
Share and Enjoy:
  • Print
  • Digg
  • Facebook
  • Sphinn
  • Google Bookmarks
  • del.icio.us
  • Mixx
  • StumbleUpon
  • email

Posted on January 8, 2010 in PHP Tutorials and has been tagged as .


Feedback for "Function to Generate a PHP Random String of Numbers and Letters"

No Comments

No comments yet.

RSS feed for comments on this post. TrackBack URL


Leave a comment


« »

Categories

Services I Offer

About Me

Andy Weigel

My name is Andy Weigel and I'm a web developer and designer in Pittsburgh, PA.

I focus on combining design with technology to build compelling, creative, easy-to-navigate web sites and custom web applications for organizations and businesses of all shapes and sizes. My specialty is WordPress. And most of all, I love what I do!

On Twitter