How to sort the position of a matrix automatically?

3

Example, I have:

$matriz = array("Tomate", "Morango", "Melancia");

I would have:

(
    [0] => Tomate
    [1] => Morango
    [2] => Melancia
)

But if I do:

unset($matriz[0]);

I'll have:

(     
        [1] => Morango
        [2] => Melancia
)

How to automatically sort them back from 0

(     
        [0] => Morango
        [1] => Melancia
)
    
asked by anonymous 24.06.2017 / 03:16

2 answers

1

Just create the array again:

$newArray = array_values($oldArray);
    
24.06.2017 / 03:35
1

You do not necessarily need to create another variable, you can use it and override the values:

$matriz = array_values($matriz);

If you always get only the first value from the array, array_shift() is commonly used, since it automatically reorders the array:

array_shift($matriz);
    
24.06.2017 / 04:25