Jump to content

if i < 10 then add a leading 0


jarv

Recommended Posts

hi,

 

I would like to add a leading 0 to my FOR loop

 

for ($i=0; $i<23; $i++)
if($i<10){
$i = 0$i;
}
  {
  echo "<option value=".$i.">" . $i . "</option>";
  }

this gives and error: unexpected T_VARIABLE

 

at the moment I have:

 

0

1

2

3

4

5

6

7

8

9

 

I would like:

 

00

01

02

03

04

05

06

07

08

09

Link to comment
https://forums.phpfreaks.com/topic/232742-if-i-10-then-add-a-leading-0/
Share on other sites

That's because you don't have curly braces around the statements within your FOR loop, so what you're effectively doing is:

 

for ($i=0; $i<60; $i++)
{
    if($i>10)
    {
        $i = sprintf("%02d",$i);
    }
}

echo "<option value=".$i.">" . $i . "</option>";

 

In which case only the last value of $i (60) will be shown. In PHP you can add curly braces around any block of code even without a control statement, so this is perfectly valid:

 

{
    echo "<option value=".$i.">" . $i . "</option>";
}

 

And is why your code appeared to be somewhat structured correctly, but in-fact isn't.

 

Try:

 

for ($i=0; $i<60; $i++)
{
    if($i>10)
    {
        $i = sprintf("%02d",$i);
    }

    echo "<option value=".$i.">" . $i . "</option>";
}

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.