wamp
wamp

Reputation: 5949

How to modify the key of an array this way in PHP?

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

Upvotes: 2

Views: 141

Answers (3)

Select0r
Select0r

Reputation: 12628

$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.

Upvotes: 1

Mchl
Mchl

Reputation: 62359

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

Upvotes: 0

codaddict
codaddict

Reputation: 454920

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

Upvotes: 2

Related Questions