user3010383
user3010383

Reputation: 91

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" />

Upvotes: 3

Views: 43702

Answers (7)

hasnath rumman
hasnath rumman

Reputation: 113

<select name="year">
    <?php for ($i = 0; $i <= 9; $i++) : ?>
         <option value='<?= $i; ?>' <?= $fetchData->year == $i ? 'selected' : '' ?>><?= $i; ?></option>
    <?php endfor; ?>
</select>

Upvotes: 0

jade290
jade290

Reputation: 433

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>

Upvotes: 1

SpiderLinked
SpiderLinked

Reputation: 373

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

Upvotes: 1

Harshal
Harshal

Reputation: 3622

Just echo the <option> tag

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

Upvotes: 0

wapper20
wapper20

Reputation: 1

place an echo in your loop to output your options.

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

Upvotes: 0

sudee
sudee

Reputation: 783

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" />

Upvotes: 9

MeNa
MeNa

Reputation: 1487

You forgot something..

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

Upvotes: 0

Related Questions