JM4
JM4

Reputation: 6788

Add characters to month loop?

I currently have a php loop running exactly how I need it with proper validations (in both php and javascript) with one exception, if the month is less than 2 digits, (i.e. 1,2,3,4), I need for a '0' to appear before:

01 - January
02 - February
...
10 - October

My code for the loop is currently:

<select name="Month">
  <option value="">Month</option> 
  <?php
  for ($i=1; $i<=12; $i++)
  {
    echo "<option value='$i'";
    if ($fields["Month"] == $i)
      echo " selected";
    echo ">$i</option>";
  }
  ?>            
</select>

Also note, this month date is being stored in session, not interested in printing to screen

Upvotes: 2

Views: 295

Answers (2)

Christian Mann
Christian Mann

Reputation: 8125

Use sprintf($format, [$var, [$var...).

Here, have some code:

function padLeft($char, $s, $n) {
    return sprintf("%" . $char . $n . "d", $s);
}
function padWithZeros($s, $max_length) {
    return padLeft('0', $s, $max_length);
}

Upvotes: 1

Mike B
Mike B

Reputation: 32145

Try this when outputting the month:

sprintf("%02d", $month); // 01, 02 .. 09, 10, 11...

Upvotes: 7

Related Questions