skip to Main Content
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

4

Answers


  1. public static function generateReceiptNumber(int $id)
    {
        // Handle the special case when $id is 100000000
        if ($id === 100000000) {
            return '000001';
        }
    
        // Use modulo to limit the ID to the range 0 to 99,999,999
        $limited_id = $id % 100000000;
        
        // Format the limited ID with leading zeros to ensure at least 6 digits
        $receipt_number = sprintf('%06d', $limited_id);
        
        return $receipt_number;
    }
    

    please check this answer if it will help you.

    Login or Signup to reply.
  2. public static function generateReceiptNumber(int $id)
    {
         return str_pad((string)$id,6,"0",STR_PAD_LEFT);
    }
    

    This method does not have maximum cap, you can use simply add a condition to do so if really needs

    Login or Signup to reply.
  3. How about this:

    function generateReceiptNumber(int $id)
    {
        while($id>=100000000)
            $id -= 100000000 - 1;
        return sprintf('%06d', $id);
    }
    
    Login or Signup to reply.
  4. Just use the max and min functions to make it an elegant one liner.

    function generateReceiptNumber(int $id){
       return sprintf('%06d', max(1, min($id,100000000) % 100000000));
    }
    

    Live Demo

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search