1

I have this code :

 if (is_dir($dir)) {
            if ($dh = opendir($dir)) {
                while (($file = readdir($dh)) !== false) {
                    print_r(" ".$file. " ");
                    $data = array(
                        'emplacement' => 'uploads/slidesFiles/'.$file
                    );
                    $jpgId = $CI->dataaccess::InsertJpg($data);
                    $data = array(
                        'idSlideZip' => $zipId,
                        'idSlideJpg' =>$jpgId
                    );
                    $CI->dataaccess::InsertJpgToSlide($data);
                }
                closedir($dh);
            }
        }

My folder :

folder order

But when I am using the read dir function to loop into my folder, I dont have the expected order wich is the next :

read dir order

I tried to reorder with the sort function but that is not the result expected.

sort order

Any idea ?

guiz
  • 99
  • 1
  • 7

1 Answers1

2

Looks like you're suffering from lexicographic sorting.

What you need is natsort().

Alphabetical:

1, 10, 2, 3

Natsort:

1, 2, 3, 10

The reason for this is because the elements in your array are treated as strings, so every character in the string is treated as a character and not an integer.

Further reading.

Mark
  • 1,852
  • 3
  • 18
  • 31
  • 1
    Ty Couldn't see this function in this doc : https://www.w3schools.com/php/php_arrays_sort.asp – guiz Feb 11 '20 at 15:14
  • Just as a general rule it's always best to refer to [PHP.net](https://www.php.net/) when looking at functions, W3Schools is notoriously unreliable. – Mark Feb 11 '20 at 15:22