Skip to content

Instantly share code, notes, and snippets.

@jakeasmith
Created November 30, 2012 16:26
Show Gist options
  • Save jakeasmith/4176790 to your computer and use it in GitHub Desktop.
Save jakeasmith/4176790 to your computer and use it in GitHub Desktop.
Random string generator
<?php
/*
* Coupon code generator
*/
$num_of_coupons_to_generate = 100;
$coupon_count = 0;
while($coupon_count != $num_of_coupons_to_generate)
{
echo generate_coupon() . PHP_EOL;
$coupon_count++;
}
function generate_coupon()
{
$alph = 'ABCDEFGHJKMNPQRSTUVWXY';
$num = '23456789';
return 'V2-' .
get_random_string($alph, 2) .
get_random_string($num, 2) .
get_random_string($alph, 2);
}
function get_random_string($valid_chars, $length)
{
// start with an empty random string
$random_string = "";
// count the number of chars in the valid chars string so we know how many choices we have
$num_valid_chars = strlen($valid_chars);
// repeat the steps until we've created a string of the right length
for ($i = 0; $i < $length; $i++)
{
// pick a random number from 1 up to the number of valid chars
$random_pick = mt_rand(1, $num_valid_chars);
// take the random character out of the string of valid chars
// subtract 1 from $random_pick because strings are indexed starting at 0, and we started picking at 1
$random_char = $valid_chars[$random_pick-1];
// add the randomly-chosen char onto the end of our string so far
$random_string .= $random_char;
}
// return our finished random string
return $random_string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment