Jump to content

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>";
}

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.