Basically, I have a bunch of files with a common prefix (logo%d.jpg
) .
When they are viewed using ls
or even when looping through a directory in PHP, I don't receive them in numerical order, meaning logo1.jpg, logo2.jpg
.
Instead I get them in alphabetical order, like:
logo1.jpg, logo10.jpg, logo11.jpg ... logo 19.jpg, logo2.jpg
(Instead of logo20.jpg
)
Is there a way to ouput them in numerical order? logo1, logo2, logo3 .. etc.
You could put them in an array and sort the array with the natsort
Docs function:
$array = array('logo1','logo2','logo12');
natsort($array);
Which gives (Demo):
array(3) {
[0]=>
string(5) "logo1"
[1]=>
string(5) "logo2"
[2]=>
string(6) "logo12"
}
The order you're looking for is often called natural order.
Alternatively, you could prefix the numbers, e.g. if you're already using sprintf
to name the files, so that the standard sort order would still work:
`logo%03d.jpg`
Which would generate
logo001.jpg
for decimal 1
.
Load into an array and use natsort()
If you're using ls
like you say...
ls | sort -n
will do the trick.