Skip to content

Lexicographically order PHP

An answer to this question on Stack Overflow.

Question

I have created a script that is taking uploaded images and name them after how many images there is in a directory. Like if there is one image in the directory it will be named 0 and the 14:th as 14. I have also created a script that takes the images and displays them on the site with the newest image at the top and oldest at the bottom, using "array_reverse()".

The order is working up to 10 images (remember the first image is 0) but the 11:th image is displayed between 1 and 2 because of the lexicographically order.

How can I prevent this without using a database?

Greatful for any answear!

EDIT

Here I've got an example:

<?php
    $title = "Click to see the full size image!";
    //upload from folder
    error_reporting(0);
    $files = glob("images/*.*");
    $files = array_reverse($files);
    
    for ($i=0; $i<count($files); $i++)
    {
    $image = $files[$i];
    echo '<a href="'.$image.'"><img src="'.$image.'" width="400px" height="300px"   title="'.$title.'"></a>';
    }

?>

Answer

You can use the natsort command for this, which applies a natural ordering to the items in your list.

For example:

<?php
  $array1 = $array2 = array("img12.png", "img10.png", "img2.png", "img1.png");
  natsort($array2);
  print_r($array2);
?>

gives:

Array
(
    [3] => img1.png
    [2] => img2.png
    [1] => img10.png
    [0] => img12.png
)