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

前端 未结 5 1541
面向向阳花
面向向阳花 2021-01-14 05:17

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;          


        
相关标签:
5条回答
  • 2021-01-14 05:26

    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
    0 讨论(0)
  • 2021-01-14 05:34

    PHP will parse 01 as an integer, so it will become 1. You can't iterate on a string like '01' so you'll have to edit the value of $i later on in your code.

    If you need a 01 later on, you could use padding. http://php.net/manual/en/function.str-pad.php

    0 讨论(0)
  • 2021-01-14 05:41

    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.

    0 讨论(0)
  • 2021-01-14 05:45

    for ($i = 01; $i <= 12; $i++) {

                $value = strlen($i);
                if($value==1){
                    $k = "0".$i;
                }else
                {
                    $k=$i;
                }
                echo "<option value='$k'";
                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>";
            }
    

    For loop can not start with 01 so you can do like this as shown above

    0 讨论(0)
  • 2021-01-14 05:47
    for ($i = 1; $i <= 25; $i++) {
    echo str_pad($i, 2, "0", STR_PAD_LEFT);
    echo "<br/>"; }
    

    it may help you..

    0 讨论(0)
提交回复
热议问题