I am looking to generate a random string based on the amount of products I have. For instance I have 100 products named “test” I want to be able to generate 100 product codes which will all be unique.
I am currently using this code:
<?php
/**
* The letter l (lowercase L) and the number 1
* have been removed, as they can be mistaken
* for each other.
*/
function createRandomPassword() {
$chars = "abcdefghijkmnopqrstuvwxyz023456789";
srand((double)microtime()*1000000);
$i = 0;
$pass = '' ;
while ($i <= 7) {
$num = rand() % 33;
$tmp = substr($chars, $num, 1);
$pass = $pass . $tmp;
$i++;
}
return $pass;
}
// Usage
$password = createRandomPassword();
echo "Your random password is: $password";
?>
Cheers
There is already a built in function that will handle this for you trivially.
uniqidgenerates a prefixed unique identifier based on the current time in microseconds.http://php.net/manual/en/function.uniqid.php
It is worth noting that to ensure true uniqueness you would need to store all the codes generated and check that no duplicated are issued.