Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP natsort keeps index

Tags:

php

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
)
like image 494
joedborg Avatar asked Sep 07 '11 12:09

joedborg


2 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);
like image 81
Jon Avatar answered Sep 22 '22 12:09

Jon


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.

like image 30
MGwynne Avatar answered Sep 23 '22 12:09

MGwynne