YeuSeChia YeuSeChia - 4 months ago 11
PHP Question

How to change the array-key with a simple summation?

I have a simple array, whose all keys are numbered by an integer:

$InpArray = array (

"-5" => "x",
"-4" => "b",
"-3" => "s",
"-2" => "e",
"-1" => "a",
"0" => "d",
"1" => "k",
"2" => "l",
"3" => "w",
"4" => "y",
"5" => "c"

);


And, I have a integer variable, like:
$MyInteger
.




Now, I want to do a simple summation to all keys (of
$InpArray
), with certain value from:
$MyInteger
. The output array is:
$OutArray
; for instance:


  • If
    $MyInteger = -1;
    ,
    $OutArray
    will be:



    $OutArray = array (

"-6" => "x",
"-5" => "b",
"-4" => "s",
"-3" => "e",
"-2" => "a",
"-1" => "d",
"0" => "k",
"1" => "l",
"2" => "w",
"3" => "y",
"4" => "c"

);



  • If
    $MyInteger = 0;
    ,
    $OutArray
    will not be changed.

  • If
    $MyInteger = +1;
    ,
    $OutArray
    will be:



    $OutArray = array (

"-4" => "x",
"-3" => "b",
"-2" => "s",
"-1" => "e",
"0" => "a",
"1" => "d",
"2" => "k",
"3" => "l",
"4" => "w",
"5" => "y",
"6" => "c"

);





How to solve this problem, with PHP language?

Answer

The easiest way is to use foreach to iterate over the input array and build a new array:

$outArray = array();

foreach ($inpArray as $key => $value) {
    $outArray[$key + $MyInteger] = $value;
}

// That's all, folks!