phpnumber-formattingdigitszero-padding

How to pad single-digit numbers with a leading 0


I am looping an array of one-digit and two-digit numbers.

When printing these values, I need to ensure that all values are shown as two-digit numbers.

I need a solution to prepend zeros to the single-digit numbers but leave the two-digit numbers unchanged.

In other words, I want to "left pad" a numeric string to a minimum of two digits by adding zeros.

How can I change my code to render leading 0's for values 1 through 9?

<?php foreach (range(1, 12) as $month): ?>
    <option value="<?=$month?>"><?=$month?></option>
<?php endforeach ?>

Expected result:

<option value="01">01</option>
<option value="02">02</option>
<option value="03">03</option>
<option value="04">04</option>
<option value="05">05</option>
<option value="06">06</option>
<option value="07">07</option>
<option value="08">08</option>
<option value="09">09</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>

Solution

  • <?php foreach (range(1, 12) as $month): ?>
      <option value="<?= sprintf("%02d", $month) ?>"><?= sprintf("%02d", $month) ?></option>
    <?php endforeach?>
    

    You'd probably want to save the value of sprintf to a variable to avoid calling it multiple times.