4

The documentation for glob doesn't mention what order (if any) it returns the array of pathnames in, however, it does mention a flag that allows you to disable sorting.

GLOB_NOSORT - Return files as they appear in the directory (no sorting)

How is the array sorted by glob when when the GLOB_NOSORT flag is not used?

FuzzyTree
  • 32,014
  • 3
  • 54
  • 85

2 Answers2

3

By default, the list is sorted ASCIIbethical in descending order, i.e A, B, C...Z, a, b, c...z, 0,1...9. Its a copy of the libc glob()

Source http://www.delorie.com/djgpp/doc/libc/libc_426.html

Also the PHP source C code for glob: https://github.com/php/php-src/blob/89a9acea1f9d821a9805b3857bf4febbba08690d/win32/glob.c#L521

Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
  • thanks, didn't want to rely on testing. the note about alphabetical sorting in libc is what i was looking for. – FuzzyTree Jul 10 '14 at 10:22
  • np, I did some research last night after you asked me on http://stackoverflow.com/questions/24665648/php-how-to-generate-indexed-name-with-string-in-file-output/24665789#comment38239916_24665789 it *should* note the sorting order in the docs, just to clarify. – Lawrence Cherone Jul 10 '14 at 10:27
  • 1
    Ive requested an edit to the docs, GLOB_NOSORT - Return files as they appear in the directory (no sorting), By default, the list is sorted alphabetically. – Lawrence Cherone Jul 10 '14 at 10:34
  • 2
    According to the source pointed to in the answer, the order is actually **[ASCIIbethical](https://en.wikipedia.org/wiki/ASCII#Character_order)**, and **ascending**. It's evident from the `qrsort` call right next to the line that Lawrence's link points to. It uses a comparator function based on `strcmp`, which simply compares character codes. There may be subtle differences between OSes in the ordering of locale-specific characters (depending on the encoding used by the OS), but the standard English subset is being sorted in the ASCII order (eg. uppercase letters before lowercase letters). – ksadowski Oct 04 '18 at 17:47
  • This answer is wrong. As ksadowski said, sorting is ASCIIbethical, and ascending, like this : A, B, C...Z, a, b, c...z – Chrysotribax Nov 03 '21 at 12:14
  • @Chrysotribax updated – Lawrence Cherone Nov 03 '21 at 16:21
1

Worth noting that in my experience I am getting files ordered like this

Alpha.txt
Beta.txt
Zebra.txt
alpha.txt
beta.txt
zebra.txt

This is on linux

It would be best to have

Alpha.txt
alpha.txt
Beta.txt
beta.txt
Zebra.txt
zebra.txt
Mark
  • 39
  • 1
  • 6