Delete item from an array and reorder it - PHP

3

It is the following:

I have an array, more or less like this:

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

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

unset ($ array [2]);

I could reorder it this way:

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

Is there any way to do this ???

    
asked by anonymous 24.04.2017 / 06:11

1 answer

7

Answering the question ...

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

array array_values ( array $input )

Demonstrating in your code:

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

unset($array[2]);

$array = array_values( $array );

Result:

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 ordering at once with this function:

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

Applying in your code, this is enough:

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

array_splice( $array, 2, 1 );

See working at IDEONE .


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

Important: array_splice works right in array . In this case you should not use $array = array_splice( $array, 2, 1 ); , otherwise the effect will be the inverse. Return is what was removed, not what's left.

    
24.04.2017 / 06:16