Formatting a number with leading zeros in PHP

Viewed 681145

I have a variable which contains the value 1234567.

I would like it to contain exactly 8 digits, i.e. 01234567.

Is there a PHP function for that?

11 Answers
$no_of_digit = 10;
$number = 123;

$length = strlen((string)$number);
for($i = $length;$i<$no_of_digit;$i++)
{
    $number = '0'.$number;
}

echo $number; ///////  result 0000000123

You can always abuse type juggling:

function zpad(int $value, int $pad): string {
    return substr(1, $value + 10 ** $pad);
}

This wont work as expected if either 10 ** pad > INT_MAX or value >= 10 * pad.

Related