Force number to be multiple digits?

Hey guys,

I’m just wondering if it’s possible to change a number from something like 6 to 0006 using php?

I just want to be able to force the number to be 4 digits, empty digits in front should be zeros.

Thanks,
Mario

use str_pad with STR_PAD_LEFT

^ Yep. Something like:

print str_pad('6', 4, '0', STR_PAD_LEFT); 

Hey guys,

Thank you so much for the replys. It worked flawlessly with the variable being a static number. However I’m trying to get a value out of a function in wordpress.

the_category_count(4)

Thats where I get my value, the only problem is that that particular value ALWAYS jumps to the far left, and does not seem to function with the amount of digits specified.

So, is there a way where I can pull this value into a variable, then convert it to a plain number string in another variable?

Example


<?php

$input = the_category_count(4);

$input_num = $input; <-- How to make this a plain number?

echo str_pad($input_num, 4, "0", STR_PAD_LEFT);

?>

Thanks again guys,
Mario

Hi Mario,

At least two simple ways to do this:

  1. Cast as an int

$input_num = (int) the_category_count(4);
echo str_pad($input_num, 4, "0", STR_PAD_LEFT);

  1. Just use (s)printf

printf('%04d', the_category_count(4));

or


$number_string = sprintf('%04d', the_category_count(4));
echo $number_string

I definitely prefer the second approach. Every programmer should be familiar with printf and its extemely flexible formatting codes.

Cheers,
Marc