46

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?

3

6 Answers 6

144

How about array_combine?

$b = array_combine(range(1,10), range(1,10));

or (as suggested in comments):

$b = array_combine($r = range(1, 10), $r)
Sign up to request clarification or add additional context in comments.

2 Comments

how does range returns array values? When we echo range(1,10) it displays full content? confusing dude?
array_combine($r = range(1, 10), $r) avoid recall range in 2 times.
7

Or you did it this way:

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

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

Comments

0

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?

Comments

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

Comments

0
<?php

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

print_r($array);

?>

Comments

0

Create a function to make this:

if (! function_exists('sequence_equal'))
{
    function sequence_equal($low, $hight, $step = 1)
    {
        return array_combine($range = range($low, $hight, $step), $range);
    }
}

Using:

print_r(sequence_equal(1, 10, 2));

Output:

array (
  1 => 1,
  3 => 3,
  5 => 5,
  7 => 7,
  9 => 9,
)

In PHP 5.5 >= you can use Generator to make this:

function sequence_equal($low, $hight, $step = 1)
{
    for ($i = $low; $i < $hight; $i += $step) {

        yield $i => $i;
    }
}

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.