0

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>

6 Answers 6

11

This will form your array correctly using array_combine:

$array = array_combine( range(1,1000), range(1,1000));
Sign up to request clarification or add additional context in comments.

Comments

4

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]);

4 Comments

this will destroy first array, so instead 1000 list option you will get only 999
Yes it will destroy the 0th element of the array, but range(0,1000) is inclusive - there would be 1001 elements to the array it generates, therefore unsetting the 0th element would leave you with 1000 elements, 1-1000.
but if the range starting with 50, then will be wrong.
@WallaceMaxters Umm, yes, this answer would be wrong then, as what you're saying is not the original problem. Nice 4+ year necro comment, btw.
1

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>';

Comments

0

Another way is to create the array through a loop:

for ($i = 1; $i <= 1000; $i++)
    $arr[$i] = $i;

Comments

0

Just don't use value attribute at all.
So, the form will send you option instead.

Comments

-2

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>
<? } ?>

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.