0

I would like to Increment numbers with double digits if the number is less then 10

This is what i tried so far

$i = 1;

echo $i++;

results is 1,2,3,4,5,6 so on

Then i try adding a condition

$i = 1;

    if ($i++<10){    
     echo "0".$i++;
    }else{
     echo $i++;
    }

Work but skipping the numbers 2,4,6,8 so on.

Can anyone tell me the proper way to do this?

hakre
  • 193,403
  • 52
  • 435
  • 836
zack
  • 484
  • 3
  • 9
  • 25

4 Answers4

5

If the condition is only there for the leading zero you can do this much easier with this:

<?php

    $i = 10;
    printf("%02d", $i++);

?>
hakre
  • 193,403
  • 52
  • 435
  • 836
Rizier123
  • 58,877
  • 16
  • 101
  • 156
  • 2
    The second line can be even simpler by replacing `echo()` and `sprintf()` (formats the string and returns it) with `printf()` (formats the string and output it). – axiac Jan 20 '15 at 12:39
1

if you want prepend something to a string use:

echo str_pad($input, 2, "0", STR_PAD_LEFT); //see detailed information http://php.net/manual/en/function.str-pad.php
Raphael Müller
  • 2,180
  • 2
  • 15
  • 20
0

On the second fragment of code you are incrementing $i twice, that's why you get only even numbers.

Incrementing a number is one thing, rendering it using a specific format is another thing. Don't mix them.

Keep it simple:

// Increment $i
$i ++;

// Format it for display
if ($i < 10) {
    $text = '0'.$i;     // Prepend values smaller than 10 with a zero
} else {
    $text = $i;
}

// Display it
echo($text);
axiac
  • 68,258
  • 9
  • 99
  • 134
  • Or, as explained by [this answer](http://stackoverflow.com/a/28045511/4265352), use `sprintf()` instead of the `if` block. – axiac Jan 20 '15 at 12:37
0
<?php

  $i = 1;
  for($i=1;$i<15;){
    if($i<10){
      echo '0'.$i++."<br>";
    }else{
      echo $i++."<br>";
    }
  }

?>
Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
Priyank
  • 3,778
  • 3
  • 29
  • 48