Home » Php » PHP natsort keeps index

PHP natsort keeps index

Posted by: admin July 12, 2020 Leave a comment

Questions:

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
)
How to&Answers:

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);

Answer:

Just use array_values to get the values of the array and break the key-value association:

<?php

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

?>

So:

<?php

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

?>

yields:

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

See comment on natsort.