1

If I had the following array:

Array(
    [0] => 30
    [1] => 60
    [2] => 2
    [3] => 55
    [4] => 1
    [5] => 20
    [6] => 1
    [7] => 8
    [8] => 38
    [9] => 58
    [10] => 12
)

How would I delete the first element and then add a new element to the end. So the new array would look like this:

Array(
    [0] => 60
    [1] => 2
    [2] => 55
    [3] => 1
    [4] => 20
    [5] => 1
    [6] => 8
    [7] => 38
    [8] => 58
    [9] => 12
    [9] => 10
)

I could use array_push to add to the end but then how would I delete the first element and reposition the keys?

cKendrick
  • 207
  • 1
  • 4
  • 13
  • possible duplicate of [How to Remove Array Element and Then Re-Index Array?](http://stackoverflow.com/questions/5217721/how-to-remove-array-element-and-then-re-index-array) – Felix Kling Dec 14 '12 at 03:11

2 Answers2

3

array_shift will remove the first element, and shift all the keys "up" one.

$array = ('0' => '30', '1' => '20', '2' => '5');
$array = array_shift($array, '19');
$var_dump ($array); // gives 0 => 20, 1 => 5, 2 => 19
Laurence
  • 58,936
  • 21
  • 171
  • 212
2

You should use array_shift to remove/re-index your array by assigning your current array to a variable and perform:

array_shift($Array);

Then to add a new value to the Array

$Array[] = "Toadd";

You will then beable to add another number/string to your array.

Daryl Gill
  • 5,464
  • 9
  • 36
  • 69