Add leading zeros to a number – PHP function
This is an very simple function that will convert any number in a n-digit format with leading zeros. So if you need to convert 1 in 0001 the following function will help you do that.
function return_n_digits ($number_of_digits, $num)
{
$length = strlen($num);
for($i=1; $i<($number_of_digits-$length);$i++)
{
$n_digits.="0";
}
$n_digits.=$num;
return $n_digits;
}
Here is the output of the function:
echo return_n_digits(5, 1); //will output 00001
echo return_n_digits(2, 2); //will output 02
echo return_n_digits(1, 5); //will output 5
echo return_n_digits(6, 100); // will output 000100