tags:

views:

71

answers:

4

How do I have it render leading 0's for 1-9 ?

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


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

       <?php endforeach?>
+2  A: 
$month = 1;
echo sprintf("%02d", $month);
out: 01

Use sprintf

lemon
+2  A: 

Use either str_pad():

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

or sprintf():

echo sprintf('%02d', $month);
cletus
I didn't know about `str_pad`... Cool.
jheddings
A: 

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

or

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

Amit
+2  A: 
<?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.

jheddings
Perfect, this works
matthewb