Method to encapsulate numbers into 6 to 8 character limit
P粉315680565
P粉315680565 2023-08-10 10:36:59
0
2
612
<p><br /></p> <pre class="brush:php;toolbar:false;">public static function generateReceiptNumber(int $id) { $receipt_number = sprintf(' d', $id % 100000000); return $receipt_number; }</pre> <p>I am using the above code to convert the incoming $id to a minimum 6 digit, maximum 8 digit number. For example: 000001 - 99999999</p> <p>But there is a flaw in this code. When $id equals 100000000, it will return 000000. How should I improve the above code to return 000001? </p> <p>By analogy, $id is the auto-incremented ID of the database. </p> <p>The reason I want to achieve this is because I have a display text box with a text limit of only 8 digits and I can only count the numbers back up from 000001 and keep repeating. </p>
P粉315680565
P粉315680565

reply all(2)
P粉403804844




public static function generateReceiptNumber(int $id)
{
    // 处理特殊情况,当$id为100000000时     if ($id === 100000000) {
        return '000001';
    }

    // 使用取模运算将ID限制在范围0到99,999,99     $limited_id = $id % 100000000;
    
    // 格式化限制的ID,使用前导零确保至少6位     $receipt_number = sprintf('%06d', $limited_id);
    
    return $receipt_number;
}


Please see if this answer helps

P粉863295057

How about this:

function generateReceiptNumber(int $id)
{
    while($id>=100000000)
        $id -= 100000000 - 1;
    return sprintf('%06d', $id);
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template