[php] Formatting a number with leading zeros in PHP

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?

This question is related to php numbers format

The answer is


Simple answer

$p = 1234567;
$p = sprintf("%08d",$p);

I'm not sure how to interpret the comment saying "It will never be more than 8 digits" and if it's referring to the input or the output. If it refers to the output you would have to have an additional substr() call to clip the string.

To clip the first 8 digits

$p = substr(sprintf('%08d', $p),0,8);

To clip the last 8 digits

$p = substr(sprintf('%08d', $p),-8,8);

Though I'm not really sure what you want to do you are probably looking for sprintf.

This would be:

$value = sprintf( '%08d', 1234567 );

Given that the value is in $value:

  • To echo it:

    printf("%08d", $value);

  • To get it:

    $formatted_value = sprintf("%08d", $value);

That should do the trick


This works perfectly:

$number = 13246;
echo sprintf( '%08d', $number );

$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

If the input numbers have always 7 or 8 digits, you can also use

$str = ($input < 10000000) ? 0 . $input : $input;

I ran some tests and get that this would be up to double as fast as str_pad or sprintf.
If the input can have any length, then you could also use

$str = substr('00000000' . $input, -8);

This is not as fast as the other one, but should also be a little bit faster than str_pad and sprintf.

Btw: My test also said that sprintf is a little faster than str_pad. I made all tests with PHP 5.6.

Edit: Altough the substr version seems to be still very fast (PHP 7.2), it also is broken in case your input can be longer than the length you want to pad to. E.g. you want to pad to 3 digits and your input has 4 than substr('0000' . '1234', -3) = '234' will only result in the last 3 digits


sprintf is what you need.

EDIT (somehow requested by the downvotes), from the page linked above, here's a sample "zero-padded integers":

<?php
    $isodate = sprintf("%04d-%02d-%02d", $year, $month, $day);
?>

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.


When I need 01 instead of 1, the following worked for me:

$number = 1;
$number = str_pad($number, 2, '0', STR_PAD_LEFT);

I wrote this simple function to produce this format: 01:00:03

Seconds are always shown (even if zero). Minutes are shown if greater than zero or if hours or days are required. Hours are shown if greater than zero or if days are required. Days are shown if greater than zero.

function formatSeconds($secs) {
    $result = '';

    $seconds = intval($secs) % 60;
    $minutes = (intval($secs) / 60) % 60;
    $hours = (intval($secs) / 3600) % 24;
    $days = intval(intval($secs) / (3600*24));

    if ($days > 0) {
        $result = str_pad($days, 2, '0', STR_PAD_LEFT) . ':';
    } 

    if(($hours > 0) || ($result!="")) {
        $result .= str_pad($hours, 2, '0', STR_PAD_LEFT) . ':';
    } 

    if (($minutes > 0) || ($result!="")) {
        $result .= str_pad($minutes, 2, '0', STR_PAD_LEFT) . ':';
    } 

    //seconds aways shown
    $result .= str_pad($seconds, 2, '0', STR_PAD_LEFT); 

    return $result;

} //funct

Examples:

echo formatSeconds(15); //15
echo formatSeconds(100); //01:40
echo formatSeconds(10800); //03:00:00 (mins shown even if zero)
echo formatSeconds(10000000); //115:17:46:40 

echo str_pad("1234567", 8, '0', STR_PAD_LEFT);

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to numbers

how to display a javascript var in html body How to label scatterplot points by name? Allow 2 decimal places in <input type="number"> Why does the html input with type "number" allow the letter 'e' to be entered in the field? Explanation on Integer.MAX_VALUE and Integer.MIN_VALUE to find min and max value in an array Input type "number" won't resize C++ - how to find the length of an integer How to Generate a random number of fixed length using JavaScript? How do you check in python whether a string contains only numbers? Turn a single number into single digits Python

Examples related to format

Brackets.io: Is there a way to auto indent / format <html> Oracle SQL - DATE greater than statement What does this format means T00:00:00.000Z? How to format date in angularjs How do I change data-type of pandas data frame to string with a defined format? How to pad a string to a fixed length with spaces in Python? How to format current time using a yyyyMMddHHmmss format? java.util.Date format SSSSSS: if not microseconds what are the last 3 digits? Formatting a double to two decimal places How enable auto-format code for Intellij IDEA?