How to sort the position of a matrix automatically?

Asked

Viewed 40 times

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 will have:

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

How to order automatically to return from 0

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

2 answers

1

Just create the array again:

$newArray = array_values($oldArray);

1

You don’t necessarily need to create another variable, you can use it and override the values:

$matriz = array_values($matriz);

If you will always take only the first value of the array, the array_shift(), since it automatically reorders the array:

array_shift($matriz);
  • Cool, never used the array_shift, about creating a new, exact, it doesn’t really need to, so I just said create the array again, may be of the same name or not.

Browser other questions tagged

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