Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

<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" />
like image 356
user3010383 Avatar asked Jul 13 '26 05:07

user3010383


2 Answers

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" />
like image 169
sudee Avatar answered Jul 15 '26 19:07

sudee


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>"; 
like image 26
SpiderLinked Avatar answered Jul 15 '26 20:07

SpiderLinked



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!