0

Here is my array:

$array = array(
   0 => 'a',
   1 => 'b',
   2 => 'c',
   3 => 'd',
   4 => 'e',
   5 => 'f',
);

Now, I want remove item at 3unset($array[3])—but this is the result:

$array = array(
   0 => 'a',
   1 => 'b',
   2 => 'c',
   4 => 'e',
   5 => 'f',
);

But I want result look like this:

$array = array(
   0 => 'a',
   1 => 'b',
   2 => 'c',
   3 => 'e',
   4 => 'f',
);

Similar with insert at 3$array[3] = 'g'—I want result look like this:

$array = array(
   0 => 'a',
   1 => 'b',
   2 => 'c',
   3 => 'g',
   4 => 'd',
   5 => 'e',
   6 => 'f'
);

How can this be done?

Giacomo1968
  • 25,759
  • 11
  • 71
  • 103
  • I posted an answer but then I realized you haven't posted what you tried. [What have you tried?](http://mattgemmell.com/2008/12/08/what-have-you-tried/) See [about Stack Overflow](http://stackoverflow.com/about). – John Conde May 15 '14 at 02:25

2 Answers2

0

Just use array_values() to "re-key" your array:

$array = array(
   0 => 'a',
   1 => 'b',
   2 => 'c',
   3 => 'd',
   4 => 'e',
   5 => 'f',
);
unset($array[3]);
$array = array_values($array);

Demo

For the second part just split the array where you want to add your new value, and it to the first part, then merge your arrays back together again.

$array = array(
   0 => 'a',
   1 => 'b',
   2 => 'c',
   3 => 'd',
   4 => 'e',
   5 => 'f',
);

$key = 3;
$first_part = array_slice($array, 0, $key);
$second_part = array_slice($array, $key);
$first_part[] = 'g';
$array = array_merge($first_part, $second_part);

Demo

John Conde
  • 217,595
  • 99
  • 455
  • 496
0

So if you use array_values like this:

$array = array_values($array);

And here it is in code:

$array = array(
   0 => 'a',
   1 => 'b',
   2 => 'c',
   3 => 'd',
   4 => 'e',
   5 => 'f',
);

unset($array[3]);

$array = array_values($array);

echo '<pre>';
print_r($array);
echo '</pre>';

The output would be:

Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => e
    [4] => f
)
Giacomo1968
  • 25,759
  • 11
  • 71
  • 103