Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP adding leading 0 to range

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>
like image 625
matthewb Avatar asked Dec 03 '22 14:12

matthewb


2 Answers

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

like image 112
jheddings Avatar answered Dec 18 '22 03:12

jheddings


Use either str_pad():

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

or sprintf():

echo sprintf('%02d', $month);
like image 40
cletus Avatar answered Dec 18 '22 02:12

cletus