">

PHP adds leading 0 to range

How to do this to conclude 0 for 1-9?

<?php foreach (range(1, 12) as $month): ?>


                  <option value="<?=$month?>"><?=$month?></option>

                <?php endforeach?>
+3
source share
4 answers
<?php foreach (range(1, 12) as $month): ?>
  <option value="<?= sprintf("%02d", $month) ?>"><?= sprintf("%02d", $month) ?></option>
<?php endforeach?>

You probably want to store the value sprintfin a variable to avoid calling it several times.

+6
source

Use str_pad():

echo str_pad($month, 2, '0', STR_PAD_LEFT);

or sprintf():

echo sprintf('%02d', $month);
+4
source
$month = 1;
echo sprintf("%02d", $month);
out: 01

Use sprintf

+2
source

if($month < 10) echo '0' . $month;

or

if($month < 10) $month = '0' . $month;

+1
source

Source: https://habr.com/ru/post/1724456/


All Articles