danyo
danyo

Reputation: 5846

random string list in php

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

Upvotes: 2

Views: 576

Answers (2)

Ryan
Ryan

Reputation: 28177

Using your function you can generate 100 random strings, i.e.

$product_names = array ();
for ($i=0; $i < 10; $i++ )
  $product_names[] = "code-" . createRandomPassword();

print_r ( $product_names );

Your question is not clear though. Do you have a naming convention you want to follow, do you want to generate codes in a pattern, such as 'product1', 'product2', ... , 'product100', etc ?

EDIT: The code above creates the following output:

Array
(
    [0] => code-opt6ggji
    [1] => code-4qfjt653
    [2] => code-8ky4xxo0
    [3] => code-dfip2o5x
    [4] => code-3e3irymv
    [5] => code-dgqk0rzt
    [6] => code-3fbeq0gr
    [7] => code-tev7fbwo
    [8] => code-idg04mdm
    [9] => code-8c2uuvsj
)

Upvotes: 2

Fraser
Fraser

Reputation: 17039

There is already a built in function that will handle this for you trivially. uniqid generates a prefixed unique identifier based on the current time in microseconds.

http://php.net/manual/en/function.uniqid.php

<?php
// loop 100 times
for ($i=0; $i<100; $i++)
{
  // print the uniqid based on 'test'
  echo uniqid('test', true);
}
?>

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.

Upvotes: 1

Related Questions