Basj
Basj

Reputation: 46463

Sort by filename with glob(..., GLOB_BRACE)

Let's say I have these files in the current folder:

a.txt
b.txtbis
c.txt
+ other files with other extensions

I want to list .txt and .txtbis files in a single list with PHP glob, and I want the result to be sorted by filename. Unfortunately:

None of them is sorted as it should.

How to have a list sorted by filename when using braces in glob?

Upvotes: 0

Views: 3990

Answers (1)

jspit
jspit

Reputation: 7703

Glob sorts the files by full path names (path + name + extension) alphabetically. If you only want to sort by (base)name, you can use usort:

$files = glob("*.{txtbis,txt}", GLOB_BRACE);

usort(
  $files, 
  function($a,$b){
    return basename($a) <=> basename($b);
  }
);

var_dump($files);

Upvotes: 1

Related Questions