4

I would like to add the years 2011-2001 in my drop-down-box (2012-2002 in next year, etc...).

Since I don't want to change my code I thought to do it in php.

I had it like this which worked:

<select name="purchaseYear" size="1">
   <?echo "<option>" . date("Y") . "</option>";?>
   <?echo "<option>" . date("Y") - 1 . "</option>";?>
   ...
</select>

Now I want to realise it with a for-loop and tried it like this:

<select name="purchaseYear" size="1">
    <?
    for ($i = 0; $i <= 9; $i++) {
       echo "<option>" . date("Y") - $i . "</option>";
    }
    ?>
</select>

Which gave me an empty drop-down-box.

What do I need to change? And why didn't it work?

1
  • What does the HTML output look like? Commented Aug 31, 2011 at 13:51

5 Answers 5

6

Try this:

<select name="purchaseYear" size="1">

<?php for ($i = 0; $i <= 9; $i++)
{
    $date = date("Y") - $i;
    echo "<option value='$date'>" . $date . "</option>";
}


?>

Just so you know: the issue was with Operator Precedence. You could also add parenthesis like this to solve the problem:

<select name="purchaseYear" size="1">

<?php for ($i = 0; $i <= 9; $i++)
{
    echo "<option>" . (date("Y") - $i) . "</option>";
}


?>

Sign up to request clarification or add additional context in comments.

Comments

2

try this way

<select name="purchaseYear" size="1">
<? for ($i = 0; $i <= 9; $i++)
    {
      echo "<option>" . (date("Y") - $i) . "</option>";
    }?>

because you do the arithmetic operation with concatenating with the string that why you have to put arithmetic operation into the () bracket

or you can first store the year in any another variable and the pass that variable into this echo statement

Comments

0
<select name="purchaseYear" size="1">   
    <?php
    for ($i = 0; $i <= 9; $i++)
    {
        ?>
        <option><?= date("Y") - $i ?></option>
        <?php
    }
    ?>
</select>

This worked for me!

I try to avoid putting HTML into echo statements if I can help it.

Comments

0

Or you can scrap the calculation in the loop body and perform it during setup:

<select name="purchaseYear" size="1">
<?php
    for ($i = date('Y'), $j = ($i - 10); $i >= $j; $i--) {
        echo '<option>', $i, '</option>', PHP_EOL;
    }
?>
</select>

Comments

-1

This:

echo "<option>" . date("Y") - $i . "</option>";

becomes this:

echo "<option>" . (date("Y") - $i) . "</option>";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.