views:

193

answers:

2

I need to dynamically create in PHP a drop-down list of numerical choices like so:

<select>
<option value="120">120 cm</option>
<option value="121">121 cm</option>
<option value="122">122 cm</option>
<option value="123">123 cm</option>
<option value="etc...
</select>

I would like to only specify the starting and ending numbers.

Thanks for any help.

+7  A: 
echo "<select>";
$range = range(120,130);
foreach ($range as $cm) {
  echo "<option value='$cm'>$cm cm</option>";
}
echo "</select>";

The range() function can handle all of the situations you described in the comment.

range(30.5, 50.5, 0.5); // 30.5, 31, 31.5, 32, etc

range(30, 50, 2); // 30, 32, 34, 36, 38, 40 etc
gnarf
Cool, never seen the range() function before. I had generally used a while loop for that scenario before.
foxed
This is really an issue of personal style, but there's nothing wrong with embedding the `range()` call directly in the `foreach`, like `foreach(range(120,130) as $cm) {`
Frank Farmer
Brilliant.How about adding control over the increment, for example if the range was from 30.5 to 50.5 to make a list like so:30.53131.532etc.or setting the increment at "2" could yield:303234etc.
dale
As I said, brilliant! Thanks!
dale
A: 
Joel Alejandro