phparrayssortingreindexnatural-sort

Naturally sort a flat array without preserving original keys


Is there any way for natsort() to also change the indexes?

I.e.

$array = array('IMG0.png', 'img12.png', 'img10.png', 'img2.png', 'img1.png', 'IMG3.png');
natsort($array);

Array
(
    [0] => IMG0.png
    [4] => img1.png
    [3] => img2.png
    [5] => IMG3.png
    [2] => img10.png
    [1] => img12.png
)

But I want:

$array = array('IMG0.png', 'img12.png', 'img10.png', 'img2.png', 'img1.png', 'IMG3.png');
natsort($array);

Array
(
    [0] => IMG0.png
    [1] => img1.png
    [2] => img2.png
    [3] => IMG3.png
    [4] => img10.png
    [5] => img12.png
)

Solution

  • array_values will effectively reindex any array passed to it with sequential integer keys. So you just need to do:

    natsort($array);
    $array = array_values($array);