Sometimes we need to generate a random alphanumeric string in code. Below PHP snippet generates a random string from given characters. You can simply use this code in your project.
<?php
function genRndString($length = 10, $chars = '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ')
{
if($length > 0)
{
$len_chars = (strlen($chars) - 1);
$the_chars = $chars{rand(0, $len_chars)};
for ($i = 1; $i < $length; $i = strlen($the_chars))
{
$r = $chars{rand(0, $len_chars)};
if ($r != $the_chars{$i - 1}) $the_chars .= $r;
}
return $the_chars;
}
}
?>
Usage:
<?php echo genRndString(); ?>

