This little php class lets you create random characters of a given length.

This little php class lets you create random characters of a given length.
 
<code class=”prettyprint”>
class RandomGenerator
{
    static $letters = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o',
                 'p','q','r','s','t','u','v','w','x','y','z');
    static $digits = array('1','2','3','4','5','6','7','8','9','0');
 
    public function genKey($length = '128') {
        $key = '';
 
        $maxIndexLeters = count(self::$letters) - 1;
        $maxIndexDigits = count(self::$digits) - 1;
 
        for ($i= 0 ; $i < $length ; $i++) {
            $makeDigit = (boolean) mt_rand(0,1);
            if ($makeDigit) {
                $index = mt_rand(0, $maxIndexDigits);
                $key .= self::$digits[$index];
            } else {
                $index = mt_rand(0, $maxIndexLeters);
                $makeUpperCase = (boolean) mt_rand(0,1);
                if ($makeUpperCase) {
                    $key .= strtoupper(self::$letters[$index]);
                } else {
                    $key .= self::$letters[$index];
                }
            }
        }
        return $key;
    }
}
echo RandomGenerator::genKey();
</code></code>

Bookmark this!

These icons link to social bookmarking sites where readers can share and discover new web pages.
  • blinkbits
  • BlinkList
  • blogmarks
  • co.mments
  • del.icio.us
  • Digg
  • Fark
  • Furl
  • MisterWong
  • NewsVine
  • Reddit
  • Spurl
  • StumbleUpon
  • TailRank
  • Technorati

One comment to “Create Random characters with given length”

  • August 10th, 2008
  • Joris

And what about ranges ?

Submit your comment

vision22.net

Copyright © 2007