Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Generate number with leading zeros and starting from 100

Tags:

php

numbers

I would like to have a function to generate numbers starting from "000100".

Right now I have the following function that allows me to generate numbers with leading zeros.

How can I modify it in order to fit my needs?

function lz( $aNumber, $intPart, $floatPart=NULL, $dec_point=NULL, $thousands_sep=NULL) 
{     
    $formattedNumber = $aNumber;
    if (!is_null($floatPart)) 
    {  
        $formattedNumber = number_format($formattedNumber, $floatPart, $dec_point, $thousands_sep);
    }

    $formattedNumber = str_repeat("0",($intPart + -1 - floor(log10($formattedNumber)))).$formattedNumber;
    return $formattedNumber;
}

Example: A new order has been placed and the order id is "19". The final order number must be 000119.

Thanks!

like image 996
Psyche Avatar asked Dec 28 '25 15:12

Psyche


2 Answers

Why not use a single printf as:

printf("%06d",$number); 

See it

The format specifier used is:

% - Marks the beginning of the format specifier
0 - Ensures zero filling if number being printed has fewer digits
6 - Number of digits reserved
d - We are printing an integer

EDIT:

From your edit looks like you want to add 100 to the input before formatting it. If so you can do:

printf("%06d",$number+100); 
like image 71
codaddict Avatar answered Dec 31 '25 07:12

codaddict


Simply use str_pad:

<?php
    for($i = 100; $i < 115; $i++)
        echo str_pad($i, 6, '0', STR_PAD_LEFT) . '<br>';
?>

http://codepad.viper-7.com/cI9DTO

like image 24
Alex Turpin Avatar answered Dec 31 '25 08:12

Alex Turpin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!