Search code examples
phpmathmodulo

turn a number based on passed in value to at least 6 digit and max 8 digit


public static function generateReceiptNumber(int $id)
{
     $receipt_number = sprintf('%06d', $id % 100000000);
     return $receipt_number;
}

I am having the above code to help me to transform a passed in $id to a minimum 6 digit and maximum 8 digit number. eg: 000001 - 99999999

But this code has a flaws that when the $id equal to 100000000, it will return me 000000, how can i enhance the code above to give me 000001 instead?

So and so forth, the $id is the database incremental id.

The purpose of wanted to achieve this is because, i have a display text box which the text limit is only 8 digit, i can only restarted the number back to 000001 and continue the count to repeat.


Solution

  • How about this:

    function generateReceiptNumber(int $id)
    {
        while($id>=100000000)
            $id -= 100000000 - 1;
        return sprintf('%06d', $id);
    }