问题
I am using CodeIgniter. I want to create an array to add to a dropdown which contains the numbers 1 -> 1000.
I have tried the php range()
function like so
$arr = range(1,1000);
It worked and create a dropdown from 1 to 1000.
I do have one problem though.
When select text 1
from my drop down and post, the posting value is 0
.
Because by default the keys are starting from 0
and the key is set to the dropdown value
Here is part of my drop down HTML
<select id="user-day" class="dropdown-small Verdana11-424039" tabindex="123456" name="days_of_month">
<option value="0">1</option>
<option value="1">2</option>
<option value="2">3</option>
<option value="3">4</option>
<option value="4">5</option>
<option value="5">6</option>
<option value="6">7</option>
Is there any way I can define range()
with key values?
Such that the values will become
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
回答1:
This will form your array correctly using array_combine:
$array = array_combine( range(1,1000), range(1,1000));
回答2:
You could create an array the same way you're doing it, just expand the range a bit then unset the 0th element.
$arr = range(0,1000);
unset($arr[0]);
回答3:
Another way is to create the array through a loop:
for ($i = 1; $i <= 1000; $i++)
$arr[$i] = $i;
回答4:
Just don't use value
attribute at all.
So, the form will send you option instead.
回答5:
Could use an old-fashioned for loop;
for ($i=1; $i <= 1000; $i++) {
$arr[$i] = $i;
}
print_r($arr);
Or just adjust the form population
$arr = range(1,10);
print_r($arr);
echo '<select>';
foreach ($arr as $a) {
$value = $a+1;
echo '<option value=\"'.$value.'">'.$a.'</option><br />';
}
echo '</select>';
回答6:
Use the following code
<select id="user-day" class="dropdown-small Verdana11-424039" tabindex="123456" name="days_of_month">
<?php for ($i=0; $i <= 1000; $i++) { ?>
<option value="<?php echo $i; ?>"><?php echo $i; ?></option>
<? } ?>
来源:https://stackoverflow.com/questions/8227875/how-do-i-create-an-array-for-a-range-of-values-with-keys-using-php