PHP Leading Zero for Double Digit Numbers

How to output a number with leading zero like dates and time.

In php, how do I format my numbers so that all numbers have a double digit. I am displaying the number of days in a month and have to match the date formatted for day.

Just check the number value during a loop in php to see if it’s less then 10.
Php code is below:
If so then add the leading zero to your string.

for ($num = 1; $num <= 31; $num++) {
$day = "0$num"; // add the zero
$day = "$num"; // don't add the zero
echo "<p>$day</p>";

You may also like...

9 Responses

  1. You've forgotten the closed curly bracket, hence you'd get a T_STRING error

  2. dhruv singh says:

    It's Work it

  3. ILIAS says:

    for ($num = 1; $num <= 31; $num++)
    $day = sprintf("%02d", $num);
    echo "<p>$day</p>";
    // for more info check this link:

  4. andwhyisit says:

    You are probably better of using str_pad().

  5. Jim says:

    // This logic means day is padded with a zero if it is less than 10…

    $day = ($num<10) ? "0$num" : $num;

  6. anneseash says:

    Hey, best thread! Good Ol Boys Moving

  7. Shamsudheen says:

    for ($num = 1; $num <= 31; $num++)
    $day = sprintf("%02d", $num);
    echo "$day”;

Leave a Reply