Skip to content

How to sort numeric file name in php

How to sort numeric file name in php

I had to read files in a directory and sort them in numeric order, meaning that the file name has numbers in it. Kind of like this
$unsortedArray = ["abc5.jpg", "abc3.jpg" "abc4.jpg", "abc1.jpg", "abc2.jpg"]
So if we want to sort them to get
$sortedArray = ["abc1.jpg", "abc2.jpg" "abc3.jpg", "abc4.jpg", "abc5.jpg"]
We just got to use the in-built php functions natsort and array_values (available in PHP 4 onwards). I believe that natsort is a wrapper around sort . This is also known as natural sorting or natural sort order. Code is available below
 if( natsort($unsortedArray) ) {
     // Re-index the array
     $files = array_values($files); 
     return $files;
 }
That’s all !
Enjoyed the content ? Share it with your friends !
Published inProgramming

Be First to Comment

Leave a Reply

Your email address will not be published.