-5

I want to generate a 6 character long unique key in php in which first 3 should be alphabets and next 3 should be digits.

I know about the uniqid() function but it generates 13 characters long key and also it wont fit in my requirement as I need first 3 characters as alphabets and next 3 as numbers.

Any way in which I can modify uniqid() to fit in my requirements?

I also dont want any collisions because if that happens my whole database will be wasted that is why I can't use rand function because it is very likely that I will get collisions

2 Answers2

3
 <?php
            $alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
            $numbers = "1234567890";
            $randstr = '';
            for($i=0; $i < 6; $i++){
                if($i<3){
                    $randstr .= $alphabets[rand(0, strlen($alphabets) - 1)];
                } else {
                    $randstr .= $numbers[rand(0, strlen($numbers) - 1)];
                }
            }
            echo $randstr;
    ?>

this will do the work for you

Meenesh Jain
  • 2,532
  • 2
  • 19
  • 29
3

You could create a manual randomizer like this:

<?php
$alphabet = 'abcdefghijklmnopqrstuvwxyz';
$numbers = '0123456789';

$value = '';
for ($i = 0; $i < 3; $i++) {
    $value .= substr($alphabet, rand(0, strlen($alphabet) - 1), 1);
}
for ($i = 0; $i < 3; $i++) {
    $value .= substr($numbers, rand(0, strlen($numbers) - 1), 1);
}

The $value variable will then be a string like "axy813" or "nbm449".

Oldskool
  • 34,211
  • 7
  • 53
  • 66
  • And what about collisions?What is the probability of collisions in this? – Prakhar Pathak Jun 26 '15 at 08:53
  • It can create duplicates. If you want to be sure there are never any duplicates, you need to check the value against a datasource of some kind (like a database or a file containing the values already generated) and re-create a new one if it's a duplicate. – Oldskool Jun 26 '15 at 08:55