-1

How to always show less than 2 position int number using php ?

This below code

<?PHP
for($i=0;$i<=100;$i++)
{
echo $i."<BR>";
}
?>

result will be like this

0
1
2
3
4
5
6
7
8
9
10
.
.
.
100

I want to always show less than 2 position int number. like this how can i apply my php code ?

01
02
03
04
05
06
07
08
09
10
.
.
.
100
mongmong seesee
  • 987
  • 1
  • 13
  • 24

5 Answers5

3

Just paste the lines inside your loop

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

And print $i.

Web Artisan
  • 1,870
  • 3
  • 23
  • 33
2

I don't know for sure if this works, but you can try it like this:

for($i=0;$i<=100;$i++)
{
    if($i < 10) {
        $i = "0$i";
        echo $i;
    }
    else {
        echo $i."<BR>";
    }
}
Refilon
  • 3,334
  • 1
  • 27
  • 51
2

You can use the function sprintf or the function str_pad like this ...

<?PHP
    for ($i = 0; $i <= 100; $i++)
    {
        echo sprintf('%02d', $i) . "<BR>";
    }
?>

... or this ...

<?PHP
    for ($i = 0; $i <= 100; $i++)
    {
        echo str_pad($i, 2, '0', STR_PAD_LEFT) . "<BR>";
    }
?>

Credits: https://stackoverflow.com/a/1699980/5755166

Community
  • 1
  • 1
mxscho
  • 1,990
  • 2
  • 16
  • 27
1

You could checkout the sprintf function that allows you to format the output http://php.net/manual/en/function.sprintf.php

Something like this perhaps

echo sprintf("%'.02d\n", 1);
strapro
  • 153
  • 8
1

You can use str_pad for adding 0's:

str_pad($var, 2, '0', STR_PAD_LEFT); 

The 0 will not be added if the length is greater or equal 2.

jackomelly
  • 523
  • 1
  • 8
  • 15