From the 2nd
element in $array
, increment the key by 100
, suppose the keys are all numeric.
views:
42answers:
3
+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
2010-08-25 06:45:08
So no direct api?
wamp
2010-08-25 06:46:32
@wamp I'm sifting through the manual atm but `foreach` is the only thing that comes to mind.
banzaimonkey
2010-08-25 06:47:30
If I knew a php-function like shift_array_keys_starting_from_element(), I would've posted it :)
Select0r
2010-08-25 06:49:23
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
2010-08-25 06:50:20
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
2010-08-25 06:51:35
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
2010-08-25 06:54:45
Fair points guys. I understood only 2nd element is to be moved. If more then this approach will not work well.
Mchl
2010-08-25 07:08:33
+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
2010-08-25 06:53:26