tags:

views:

42

answers:

3

From the 2nd element in $array, increment the key by 100, suppose the keys are all numeric.

+1  A: 
$new_array = array();
$count = 0;
foreach ($original_array as $key => $value)
{
  if ($count > 0)
    $new_array[$key + 100] = $value;
  else
    $new_array[$key] = $value;
  $count++;
}

Now $new_array contains your "shifted" $original_array, starting from element #2.

Select0r
So no direct api?
wamp
@wamp I'm sifting through the manual atm but `foreach` is the only thing that comes to mind.
banzaimonkey
If I knew a php-function like shift_array_keys_starting_from_element(), I would've posted it :)
Select0r
A: 

As noted in comments below, the following solution will only work well for moving a single element.

 reset($array); //moves pointer to the beginning
 next($array); //moves pointer to 2nd element
 $array[key($array)+100] = current($array); // copies current element to incremented key
 unset($array[key($array)]); //remove the element
Mchl
Wouldn't that overwrite elements if keys > 100 are present in $array before the shifting starts? Also, if I got the question right, he wanted to shift all elements starting from #2, so there's some loop needed.
Select0r
Even if you run backwards you can't assume that the array is in order, so I don't think this approach will work.
banzaimonkey
Fair points guys. I understood only 2nd element is to be moved. If more then this approach will not work well.
Mchl
+1  A: 

You can do:

$keys   = array_keys($array);          // extract keys.
$values = array_values($array);        // extract values.

for($i=1;$i<count($keys);$i++) {       // increment keys start 2nd key.
    $keys[$i] += 100;
}

$array = array_combine($keys,$values); // combine back
codaddict