Reputation: 197
I have a dynamic drop down menu which displays each value from number 1- 10:
$min_year = 1;
$max_year = 10;
$years = range($min_year, $max_year); // returns array with numeric values of 1900 - 2012
$durationHTML = '';
$durationHTML .= '<select name="duration" id="durationDrop">'.PHP_EOL;
$durationHTML .= '<option value="">Please Select</option>'.PHP_EOL;
foreach ($years as $year) {
$durationHTML .= "<option>$year</option>".PHP_EOL; // if no value attribute, value will be whatever is inside option tag, in this case, $year
}
$durationHTML .= '</select>';
What I want to do though is change the values so that it displays these values below:
1
1/2
2
2/3
3
3/4
4
4/5
5
5/6
6
6/7
7
7/8
8
8/9
9
9/10
10
My question is that how can I dynamically display these values above?
UPDATE:
$min_year = 1;
$max_year = 10;
$years = range($min_year, $max_year); // returns array with numeric values of 1900 - 2012
$durationHTML = '';
$durationHTML .= '<select name="duration" id="durationDrop">'.PHP_EOL;
$durationHTML .= '<option value="">Please Select</option>'.PHP_EOL;
for($i = 0; $i < sizeof($years); $i++)
{
$current_year = $years[$i];
$durationHTML .= "<option>{$current_year}</option";
if($i != (sizeof($years) - 1 )) //So you don't try to grab 11 because it doesn't exist.
{
$next_year = $years[$i+1];
$durationHTML .= "<option>{$current_year}/{$next_year}</option>";
}
}
$durationHTML .= '</select>';
Below is what it outputs:
11/2
22/3
33/4
44/5
55/6
66/7
77/8
88/9
99/10
10
Upvotes: 0
Views: 57
Reputation: 3550
Something like this should work for you;
$min_year = 1;
$max_year = 10;
$years = range($min_year, $max_year); // returns array with numeric values of 1900 - 2012
$durationHTML = '';
$durationHTML .= '<select name="duration" id="durationDrop">'.PHP_EOL;
$durationHTML .= '<option value="">Please Select</option>'.PHP_EOL;
foreach ($years as $year) {
$durationHTML .= "<option>$year</option>".PHP_EOL;
if ($year != $max_year) {
$nextYear = $year + 1;
$durationHTML .= "<option>$year / $nextYear</option>".PHP_EOL;
}
}
$durationHTML .= '</select>';
Upvotes: 1
Reputation: 144
There are probably several ways you could do this.
The easiest would be to change your foreach loop to a simple for loop, and grab the next value and use that to form your fraction. I did this so it would be easier to read, but you don't need to store the current_year and next_year in variables, you could just echo them directly from the array.
for($i = 0; $i < sizeof($years); $i++)
{
$current_year = $years[$i];
echo "<option>{$current_year}</option";
if($i != (sizeof($years) - 1 )) //So you don't try to grab 11 because it doesn't exist.
{
$next_year = $years[$i+1];
echo "<option>{$current_year}/{$next_year}</option>";
}
}
Upvotes: 0