Easy question, I filled my array the following way:
$options = range(1, 10);
This will result:
array
(
[0] => 1
[1] => 2
etc. etc.
)
This is not the result I want..
I need my array like this:
array
(
[1] => 1
[2] => 2
etc.
)
How to accomplish this easy task?
Andreas Wong
60.7k19 gold badges112 silver badges123 bronze badges
asked Apr 24, 2012 at 7:40
user443346
-
2not that i want to say you shouldn't, but please be aware that in computer science we start counting with 0, not with 1. So if you have an array starting with index 1, you have an array which is "missing" the first index. So only move up the array indices if you have a valid reason to!giorgio– giorgio2012年04月24日 07:43:30 +00:00Commented Apr 24, 2012 at 7:43
-
My valid reason is as follow: Selectbox with value 1, option 1 and so on.user443346– user4433462012年04月24日 07:47:59 +00:00Commented Apr 24, 2012 at 7:47
-
@Jordy just add 1 while displaying it ;)Yoshi– Yoshi2012年04月24日 07:48:32 +00:00Commented Apr 24, 2012 at 7:48
-
Well I'll fill my selectbox with CakePHP so it's a bit different.user443346– user4433462012年04月24日 09:52:10 +00:00Commented Apr 24, 2012 at 9:52
5 Answers 5
answered Apr 24, 2012 at 7:44
Vytautas
3,5391 gold badge30 silver badges43 bronze badges
<?php
for( $i = 1; $i <= 10; $i ++ ) {
$array[$i] = $i;
}
Voila. :)
answered Apr 24, 2012 at 7:41
Berry Langerak
18.9k5 gold badges49 silver badges62 bronze badges
Comments
if you want a one-liner instead of a for-loop like Berry suggested, just use array_combine:
$array = array_combine(range(1,10),range(1,10));
answered Apr 24, 2012 at 7:44
oezi
51.9k10 gold badges102 silver badges119 bronze badges
2 Comments
StefanNch
yeah ... for vs 3 function calls!
function myRange($start, $limit, $step)
{
$myArr = array();
foreach((array) range($start, $limit,$step) as $k => $v)
{
$myArr[$k+1] = $v;
}
return $myArr;
}
print_r(myRange(0, 100, 10));
?>
Result ------
Array
(
[1] => 0
[2] => 10
[3] => 20
[4] => 30
[5] => 40
[6] => 50
[7] => 60
[8] => 70
[9] => 80
[10] => 90
[11] => 100
)
Muhammad Omer Aslam
23.9k9 gold badges47 silver badges69 bronze badges
answered Apr 24, 2012 at 8:15
ieatbytes
5161 gold badge7 silver badges14 bronze badges
Comments
Or just shift the array
foreach ( $array as $key => $val )
$result[ $key+1 ] = $val;
Comments
lang-php