I have a content directory to be returned in descending natural order.
I\'m using scandir()
and natsort()
, but the addition of array_reve
If your image names will be in the format 123-image_name.jpg
, 2323-image_name.jpg
, ... this will do:
/**
* Compares digits in image names in the format "123-image_name.jpg"
*
* @param string $img1 First image name
* @param string $img2 Second image name
* @return integer -1 If first image name digit is greater than second one.
* 0 If image name digits are equal.
* 1 If first image name digit is smaller than second one.
*/
function compareImageNames($img1, $img2){
$ptr = '/^(\d+)-/'; // pattern
// let's get the number out of the image names
if (preg_match($ptr, $img1, $m1) && preg_match($ptr, $img2, $m2)) {
$first = (int) $m1[0]; // first match integer
$second = (int) $m2[0]; // second match integer
// equal don't change places
if($first === $second) return 0;
// if move first down if it is lower than second
return ($first < $second) ? 1 : -1;
} else{
// image names didn't have a digit in them
// move them to front
return 1;
}
}
// sort array
usort($images, 'compareImageNames');