Create Random characters with given length
- July 23rd, 2007
- php, Snippet-library
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>
















One comment to “Create Random characters with given length”
- August 10th, 2008
- Joris
August 10th, 2008 at 3:14 pmAnd what about ranges ?
Submit your comment