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?

1

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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
)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.