Skip to content Skip to sidebar Skip to footer

Create A Php Dropdown Menu From A For Loop?

I am trying to create a drop down menu with the options of 1,2,3 and 4. The below code is what I am using just now and the dropdown is empty. Any idea what I am doing wrong?

Solution 1:

You are not outputting the option tags. Try it like this:

<selectname="years"><?phpfor($i=1; $i<=4; $i++)
{

    echo"<option value=".$i.">".$i."</option>";
}
?><optionname="years"></option></select><inputtype="submit"name="submitYears"value="Year" />

Solution 2:

You basically use html without closing the php syntax.Your code should look like this:

<selectname="years"><?phpfor($i=1; $i<=4; $i++)
     {
      ?><optionvalue="<?phpecho$i;?>"><?phpecho$i;?></option><?php
        }
        ?><optionname="years"></option></select><inputtype="submit"name="submitYears"value="Year" />

Or are you trying to echo the option? In that case you forgot the echo statement:

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

Solution 3:

This worked for me. It populates years as integers from the current year down to 1901:

<selectName='ddlSelectYear'><optionvalue="">--- Select ---</option><?phpfor ($x=date("Y"); $x>1900; $x--)
              {
                echo'<option value="'.$x.'">'.$x.'</option>'; 
              } 
            ?></select>

Solution 4:

You forgot something..

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

Solution 5:

place an echo in your loop to output your options.

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

Post a Comment for "Create A Php Dropdown Menu From A For Loop?"