How to rename indexes in array?

Hi guys,

I have this array below,


Array
(
    [0] => 11
    [1] => 15
    [2] => 16
    [3] => 34
)

I want to rename the indexes, to look like below,


Array
(
    [1] => 11
    [2] => 15
    [3] => 16
    [4] => 34
)

How to do this using foreach()?

By the way this is what I’ve tried so far.


foreach ($strlesson_storage as $k=>$v)
{
 	$new_key = $k++;
	$old_key = $k;
	$strlesson_storage[$new_key] = $strlesson_storage[$old_key];
	unset($strlesson_storage[$old_key]);
}			

But I have error message below,


Severity: Notice
Message: Undefined offset: 4
Filename: controllers/admin.php
Line Number: 713

Thanks in advance.

I figured it out.
I have store the keys and values into another array variable name.
It also avoid array key/index colision.

Problem solved!

The problem you were having is that PHP array keys start a 0 therefor you have a count( $items) = 4 and the keys range from 0…3

The error message “Message: Undefined offset: 4” states that there is no array key item 4.



// Create array
$strlesson_storage = array
(
    11,
    15,
    16,
    34,
);

print_r($strlesson_storage);
// Output
Array
(
    [0] => 11
    [1] => 15
    [2] => 16
    [3] => 34
)

// Insert new item at the beginning of the array:
array_unshift($strlesson_storage, 'NEW FIRST ITEM');
print_r($strlesson_storage);
// New Output
Array
(
    [0] => NEW FIRST ITEM
    [1] => 11
    [2] => 12
    [3] => 15
    [4] => 16
)