2

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
4
  • 2
    not 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! Commented Apr 24, 2012 at 7:43
  • My valid reason is as follow: Selectbox with value 1, option 1 and so on. Commented Apr 24, 2012 at 7:47
  • @Jordy just add 1 while displaying it ;) Commented Apr 24, 2012 at 7:48
  • Well I'll fill my selectbox with CakePHP so it's a bit different. Commented Apr 24, 2012 at 9:52

5 Answers 5

6

Maybe like this:

$options = range(0, 10);
unset($options[0]);

working example

answered Apr 24, 2012 at 7:44
Sign up to request clarification or add additional context in comments.

2 Comments

that won't give the expected result, the array would start with value 2 (for key 1).
argh, sorry, my fault - didn't notice you started the range at 0... +1 for you and shame on me.
3
<?php
for( $i = 1; $i <= 10; $i ++ ) {
 $array[$i] = $i;
}

Voila. :)

answered Apr 24, 2012 at 7:41

Comments

2

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

2 Comments

You are also a badass. Thanks!
yeah ... for vs 3 function calls!
2
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

Comments

0

Or just shift the array

foreach ( $array as $key => $val )
 $result[ $key+1 ] = $val;
answered Apr 24, 2012 at 7:52

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.