Delete item from an array and reorder it - PHP

Asked

Viewed 540 times

3

Is the following:

I have an array, sort of like this:

$array = [
   [0] => 'Fellipe',
   [1] => 'Fábio',
   [2] => 'Mateus',
   [3] => 'Gustavo'
];

I would like it when I remove an item from that array:

unset($array[2]);

I could reorder it this way:

$array = [
   [0] => 'Fellipe',
   [1] => 'Fábio',
   [2] => 'Gustavo'
];

There’s some way to do it???

  • I believe that ksort/uksort does this without problems.

  • @Inkeliz from what I understand, he wants to reindexar the keys ( leave 0 1 2, and not 0 1 3, missing the 2 which has been removed). In this case the array_values.

1 answer

8


Answering the question ...

Whenever you want to ignore the keys of an array, just use the function:

array_values ( array $input ): array

Demonstrating in your code:

$array = [
   0 => 'Fellipe',
   1 => 'Fábio',
   2 => 'Mateus',
   3 => 'Gustavo'
];

unset($array[2]);

$array = array_values( $array );

Upshot:

Array
(
    [0] => Fellipe
    [1] => Fábio
    [2] => Gustavo
)

See the code working on IDEONE.


... and proposing a simpler alternative:

You can remove an item and keep sorting at once with this function:

array_splice( array &$input, int $offset [, int $length [, mixed $replacement ]] ): array

Applying in your code, just this:

$array = [
   0 => 'Fellipe',
   1 => 'Fábio',
   2 => 'Mateus',
   3 => 'Gustavo'
];

array_splice( $array, 2, 1 );

See working on IDEONE.


In the case, the 2 is the initial item to be removed, and the 1 the amount to be removed.

Important:the array_splice works directly on array. In this case it should not be used $array = array_splice( $array, 2, 1 );, otherwise the effect will be the reverse. The return is what has been removed, not what is left.

  • 1

    Man, that’s what I was looking for. Thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.