Create a PHP Dropdown menu from a for loop?

落爺英雄遲暮 提交于 2020-02-15 06:35:23

问题


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?

<select name="years">
<?php 

for($i=1; $i<=4; $i++)
{

"<option value=".$i.">".$i."</option>";
}
?> 
     <option name="years"> </option>   
        </select> 

            <input type="submit" name="submitYears" value="Year" />

回答1:


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

<select name="years">

<?php 

for($i=1; $i<=4; $i++)
{

    echo "<option value=".$i.">".$i."</option>";
}
?> 
     <option name="years"> </option>   
</select> 

<input type="submit" name="submitYears" value="Year" />



回答2:


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

 <select name="years">
    <?php 

    for($i=1; $i<=4; $i++)
     {
      ?>

     <option value="<?php echo $i;?>"><?php echo $i;?></option>
    <?php
        }
        ?> 
 <option name="years"> </option>   
    </select> 

        <input type="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>"; 



回答3:


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

        <select Name='ddlSelectYear'>
            <option value="">--- Select ---</option>

            <?php
            for ($x=date("Y"); $x>1900; $x--)
              {
                echo'<option value="'.$x.'">'.$x.'</option>'; 
              } 
            ?> 
        </select>



回答4:


You forgot something..

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




回答5:


place an echo in your loop to output your options.

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



回答6:


Just echo the <option> tag

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


来源:https://stackoverflow.com/questions/20177788/create-a-php-dropdown-menu-from-a-for-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!