1

I have an array like below,

[test] => Array
        (
            [0] => 1
            [1] => 3
            [2] => 5
            [3] => 13
            [4] => 32
            [5] => 51
        )

i need to change this array into like below,

[test] => Array
            (
                [2] => 1
                [4] => 3
                [6] => 5
                [8] => 13
                [10] => 32
                [12] => 51
            )

i need to change the key value. How can i do this?.

1
  • Is there any pattern in keys or is this just values? Commented Dec 13, 2012 at 12:53

2 Answers 2

4
$newArray = array_combine(
    range(2,count($originalArray)*2,2),
    array_values($originalArray)
);
Sign up to request clarification or add additional context in comments.

2 Comments

typo: array_keys( not needed, otherwise +1
True enough, the array_keys() is just overhead: editing to remove it
0

The array_values() function returns an array containing all the values of an array and also it reset all the keys. you can do it as

$arr = array(0 => 1, 1 => 3, 2 => 5, 3 => 13, 4 => 32, 5 => 51);
$count = 1;
$tempArr = array();
foreach ($arr as $key => $val) {
    $tempArr[$count * 2] = $val;
    $count++;
}
var_dump($tempArr);exit;

Try this code at your side.

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.