I am using the range() function to create an array. However, I want the keys to be the same as the value. This is ok when i do range(0, 10) as the index starts from 0, however if i do range(1, 11), the index will still start from 0, so it ends up 0=>1 when i want it to be 1=>1

How can I use range() to create an array where the key is the same as the value?

share|improve this question
Why not just not use the key at all? – Ignacio Vazquez-Abrams Mar 19 '11 at 5:22
im using a library i cannot modify that requires this >.< – Ozzy Mar 19 '11 at 6:07

5 Answers

up vote 21 down vote accepted

How about array_combine?

$b = array_combine(range(1,10), range(1,10));
share|improve this answer

There is no out of the box solution for this. You will have to create the array yourself, like so:

$temp = array();
foreach(range(1, 11) as $n) {
   $temp[$n] = $n;
}

But, more importantly, why do you need this? You can just use the value itself?

share|improve this answer

Or you did it this way:

$b = array_slice(range(0,10), 1, NULL, TRUE);

Find the output here: http://codepad.org/gx9QH7ES

share|improve this answer
<?php
function createArray($start, $end){
  $arr = array();
  foreach(range($start, $end) as $number){
    $arr[$number] = $number;
  }
  return $arr;
}

print_r(createArray(1, 10));
?>

See output here: http://codepad.org/Z4lFSyMy

share|improve this answer
<?php

$array = array();
foreach (range(1,11) as $r)
  $array[$r] = $r;

print_r($array);

?>
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.