HOWTO: Create a random alpha-numeric string in PHP

Creating an alpha-numeric string in PHP is easy, but having a quick function you can call is better!

This is very useful for things like password generators.

To see how to do this in Python, check out this post: …howto-create-a-random-alpha-numeric-string-in-python

To see how to do this in Perl check out this post: …howto-create-a-random-alpha-numeric-string-in-perl


<?php
function makeID($size = 6) {
    global $makeIDpool;
    $makeIDpool = array_merge(range(0,9), range('a','z'), range('A','Z'));
    $append = function ($value){ global $makeIDpool; return $makeIDpool[rand(0,count($makeIDpool) - 1)]; };
    return implode('', array_map($append, range(0,$size - 1)));
}
?>

Example:

This code sample:


print makeID().'<br />';
print makeID(10).'<br />';
print makeID(20).'<br />';
print makeID(1).'<br />';

Will print something like this:

KNHtkn
2z8ksLDSkp
bfn5X5jF5dTZ3itt9HWy
q

Did you find this post useful or have questions or comments? Please let me know!

This entry was posted in How Tos, php, Programming. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *