in html <select>, php code to add <option>s
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 w开发者_JS百科ant 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?
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>";
}
?>
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
<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.
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>
This:
echo "<option>" . date("Y") - $i . "</option>";
becomes this:
echo "<option>" . (date("Y") - $i) . "</option>";
精彩评论