1

I want to generate alphanumeric unique numbers but the format should be like this

that should be starts from AA001 to AA999 after that AB001 to AB999 .... BA001 to BA999 end with ZZ999. if i give the input is

  1 = result AA001
 999  = result AA999
 1000 = result AB001 

any one can help this ?

2
  • 1
    shouldn't it be result AB000 for 1000 ? Commented Dec 13, 2011 at 13:16
  • yes ... :-( that should be AB001... Commented Dec 13, 2011 at 13:18

2 Answers 2

6

Complete solution (see it running):

function formatNum1000($num) {
  $tail =       $num % 1000;
  $head = (int)($num / 1000);
  $char1 = chr(ord('A') + (int)($head / 26));
  $char2 = chr(ord('A') +      ($head % 26));

  return sprintf('%s%s%03d', $char1, $char2, $tail);
}

function formatNum999($num) {
  $tail =      (($num - 1    ) % 999) + 1;
  $head = (int)(($num - $tail) / 999);
  $char1 = chr(ord('A') + (int)($head / 26));
  $char2 = chr(ord('A') +      ($head % 26));

  return sprintf('%s%s%03d', $char1, $char2, $tail);
}

$ns = array(1, 500, 999, 1000, 1998, 1999, 2000, 25974, 25975, 25999, 26000, 675324, 675999);
foreach($ns as $n) {
  $formatted1000 = formatNum1000($n);
  $formatted999  = formatNum999 ($n);
  echo "Num: $n => $formatted1000 / $formatted999\n";
}

Note: you need to make sure that the input number is within the valid range (0...675999 when including 000-numbers, 1...675324 otherwise)

Note: answer revised, missed the point earlier that 000 is not allowed

Sign up to request clarification or add additional context in comments.

2 Comments

its looks better that for loop but i will always use the mysql auto increment value (primary key) to generate this unique id. if the number is 676000 i am getting value "[A676" so its a problem with this function...
It's not a problem with this function. The problem is that you didn't define what should happen after "AA999", so I decided to leave the behavior undefined. You could make the function throw an exception, or implement a third (fourth, fifth, ...) letter. I thought I'd leave this as a homework exercise, since it's pretty straightforward to add to my solution.
3

How about:

$start = 'AA997';
for($i = 0; $i < 5; $i++) {
    $start++;
    if (substr($start, 2) == '000') continue;
    echo $start,"\n";
}

output:

AA998
AA999
AB001
AB002

1 Comment

The substr function not working the input value 676000.. so i changed to explode ....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.