Hi Every Body

How I can add leading zeros in a number for example
if No. is 4 it should display 0004
if No. is 41 it should display 0041
if No. is 441 it should display 0441

Please give some hint.

Recommended Answers

try with this

$number = 41;
printf("%04d\n", $number);

printf() in php, follows some internally implemented rules for formating the numbers based on the given expression in the left side of the statemnt as shown above

please see manual for more details about this method

let me know the status

Jump to Post

All 4 Replies

how about trying this one
assuming $num is the number you want to fill

$num = "4";
$len = strlen($num);

$zeros = 5-$len;    
$no = "";
for($x=1;$x<=$zeros;$x++){
    $no .="0";
}
$no = $no.$num;
echo $no;

try with this

$number = 41;
printf("%04d\n", $number);

printf() in php, follows some internally implemented rules for formating the numbers based on the given expression in the left side of the statemnt as shown above

please see manual for more details about this method

let me know the status

happy coidng

commented: ahahah cool i really didnt think of that thing nice job +4

to be more specific str_pad() does well for this kind of requirement

$input = "41";
echo str_pad($input, 10,"0", STR_PAD_LEFT);                  

please check this too

Member Avatar

I use the str_pad method for this sort of thing, but can I ask why you need this? Is it necessary?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.20 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.