How to pad single-digit numbers with a leading 0

<?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.

Leave a Comment