Question

i have a few hundred xhtml files the names of which i push to an array. the naming convention is p0x.xhtml where x is 1-400. i'm trying to natsort the array but the leading p seems to be conflicting with the sorting.

as a last resort i can rename the files, but want to avoid that if possible. i'd appreciate if anyone knows of a workaround.

$arr = [
    'p010.xhtml',
    'p08.xhtml',
    'p04.xhtml'
];

print_r($arr);
natsort($arr);
print_r($arr);

yields:

Array
(
    [0] => p010.xhtml
    [1] => p08.xhtml
    [2] => p04.xhtml
)
Array
(
    [0] => p010.xhtml
    [2] => p04.xhtml
    [1] => p08.xhtml
)

and desired output would be:

Array
(
    [0] => p010.xhtml
    [1] => p08.xhtml
    [2] => p04.xhtml
)
Array
(
    [2] => p04.xhtml
    [1] => p08.xhtml
    [0] => p010.xhtml
)
Was it helpful?

Solution

Well it performs as advertised, just not the way you want. You can switch to usort/uasort which allows you to provide your own comparison function, in your case a function that returns the natural order of the string minus the leading p?

function cmp($a, $b) {
   return strnatcmp ( substr($a,1) , substr($b,1) );
}

which is called as

usort($arr,'cmp');

As pointed out in another question, in php 5.3+ this can be rewritten as

usort($arr,function($a, $b) {
   return strnatcmp ( substr($a,1) , substr($b,1) );
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top