Home > database >  PHP invoice number with alpha numeric increment
PHP invoice number with alpha numeric increment

Time:01-11

The invoice number looks like this INV{Year}{Month}-1A Ex: INV202201-1A

The suffix 1A's numerical value can only go up to 9. Then the Alphabet should change to B, then the numerical value again goes to 9B then has to change to C & so on. Also when the month changes the prefix should change back to 1A. I've already tried adding all alphabets to an array but I can't seem to figure it out.

I would really appreciate it if someone can point me out the right logic for this.

CodePudding user response:

The total of 1A to 9Z is 234.

The data for $usedPostfix should be from the database or stored somewhere else.

$usedPostfix = array(
    "202112" => 220,
    "202201" => 10,
    "202202" => 0,
);

This is where we find the unused postfix to be returned.

$date =  date_format(new DateTime(), 'Ym');

function getInvoice($counter, $date)
{
    foreach (range('A', 'Z') as $char) {
        for ($i = 1; $i < 10; $i  ) {
            if ($counter > 0) {
                $counter--;
                continue;
            }
            return "INV" . $date . "-" . $i . $char;
        }
    }
}

$date is using Ym format. (e.g: 202201)

Examples:

Using $date

echo getInvoice($usedPostfix[$date], $date); // OUTPUT: INV202201-2B

Using custom $date (* for example purpose)

echo getInvoice($usedPostfix["202112"], $date); // OUTPUT: INV202201-5Y

echo getInvoice($usedPostfix["202202"], $date); // OUTPUT: INV202201-1A
  •  Tags:  
  • Related