Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I start a for-loop with 01 instead of 1?

Tags:

php

How do I start a for-loop with 01 as opposed to 1? I've tried the below, but it doesn't seem to work.

for ($i = 01; $i <= 12; $i++) {
    echo "<option value='$i'";
    if ($i == $post_response[expiremm]) { 
        echo " selected='selected'"; 
    }
    $month_text = date("F", mktime(0, 0, 0, $i+1, 0, 0, 0));
    echo ">$month_text</option>"; 
} 
like image 822
Tom Avatar asked Sep 16 '25 19:09

Tom


2 Answers

You can't really start an integer at 01, you will need to pad the value, probably using str_pad to prefix leading elements to a string:

$value = $i;
if ($i < 10) {
    $value = str_pad($i, 2, "0", STR_PAD_LEFT);
}

Note that for different unit types you will obviously need to alter the desired pad_length.

like image 153
Grant Thomas Avatar answered Sep 19 '25 12:09

Grant Thomas


01 is the octal number 1 (which is equivalent to the decimal 1 in this case). Since you want to format the output to have two digits for the number, consider using printf:

printf("<option value='%02d'", $i);
  • % marks the start of a conversion
  • 0 means "pad the string with zero"
  • 2 means "the replacement should have a minimum length of 2"
  • d means "the argument is an integer"

References:

  • PHP Manual: printf
  • PHP Manual: sprintf
like image 30
Lekensteyn Avatar answered Sep 19 '25 12:09

Lekensteyn