I have a function that generates a random number, like:
$int = random_number();
Generally, the results are 6 digits, but occasionally, it ends up being less than 6 digits. How do I add zeros to the number if it is less than 6 digits? For example, if $int
is 12345
, I turn it into 123450
.
I can easily do this with something like:
if (strlen($int) == 5) {
$int = $int.'0';
} elseif(strlen($int) == 4){
$int = $int.'00';
} //etc
But clearly there must be a better way?
strpadding this is called.
See here: https://secure.php.net/manual/en/function.str-pad.php
Example:
echo str_pad($yourRandomNumber, 6, "0", STR_PAD_LEFT);
Usually sprintf
works for this purpose, but adds a leading zeros what is not a OPs question.
$padded = sprintf('%06d', 123);
For trailing zeros with sprintf
as brilliantly mentioned by Ivar (in comments section below) the following code will work:
$padded = sprintf('%-06s', 123);
For adding trailing zeros str_pad
can be used.
$padded = str_pad($num, 6, '0', STR_PAD_RIGHT);
Note:
STR_PAD_RIGHT
is a default argument, so can be omitted.
Or you can use rand(100000,999999);
if you're not using random number with extra parameters.
$number = "878"; //the random number
$int = strlen($number);
$multiplier = 6 - $int;
if ($multiplier != 0) {
$number = $number * pow(10 , $multiplier);
}
Its simple we just multiply with 10*10*10 (the number of missing numbers).