PHP: Alphabetical with folders on top

Posted on 2011-03-09
Last Modified: 2012-05-11
I want to sort my array alphabetically, but items without a period in them should be first.

In the example below, I want the items in this order:

    [4] => Folder 1
    [2] => Folder 2
    [0] => Apples.jpg
    [3] => Oranges.png
    [1] => Pears.gif


$a = array();

$a[] = 'Apples.jpg';
$a[] = 'Pears.gif';
$a[] = 'Folder 2';
$a[] = 'Oranges.png';
$a[] = 'Folder 1';




Open in new window

Question by:hankknight
LVL 38

Accepted Solution

Aaron Tomosky earned 250 total points
ID: 35090409
Split the arrays so folders and files are seperate, sort each array, merge them together
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 150 total points
ID: 35090575
It looks like the $a variable that you have handcoded in the example is really the result of reading a directory and aggregating the files and folders that are part of this directory.  Is that right?  If not, please show us where this data comes from.  If so, create two arrays.

You might want to use glob() or readdir() to access the directory.

Then you can apply the built-in PHP functions to decide which of the two arrays to put them in.

Once that is done, sort the two arrays to get the directory and file names in the right order.

Then create the output or combine the arrays in the way that you want.

HTH, ~Ray
LVL 34

Assisted Solution

by:Beverley Portlock
Beverley Portlock earned 100 total points
ID: 35093346
There is a question I dealt with to do something very similar. By extending the class and changing the sort criteria it will do what you want.

The altered  version is below. You will need to change the data in the test code at the bottom to try it out on your own folders especially this $pathToStartAt = "/path/to/folder"; line. Put a full path in. I have also inserted a line near the top to enable error_reporting during testing but it can be removed later


ini_set('display_errors',1); error_reporting(E_ALL);

class FileData {

     public $fileDate;
     public $fileName;
     public $filePath;
     public $fileSize;
     public $folderSort;
     function __construct( $p, $n, $d, $s, $t ) {
          $this->filePath = $p;
          $this->fileName = $n;
          $this->size = $s;
          $this->fileDate = $d;
          $this->folderSort = ( strtolower($t) == "file" ) ? 1 : 0;

     function FileCompareSort( $a, $b ) {

          // Build composite keys for sorting
          $aKey = sprintf("%02d%s", $a->folderSort, $a->fileName );
          $bKey = sprintf("%02d%s", $b->folderSort, $b->fileName );

          // Compare
          if ( $aKey < $bKey )
               return -1;
               if ( $aKey > $bKey )
                    return 1;

          return 0;

     function searchDir( $pathToDirectory, & $results ) {

          // Make sure the directory has a trailing slash
          if ( substr( $pathToDirectory, -1, 1 ) != "/" )
               $pathToDirectory .= "/";

          // Get list of files in directory
          if ( $fileList = opendir( $pathToDirectory ) ) {
               while ( $aFile = readdir( $fileList ) ) {

                    if ( $aFile == "." || $aFile == ".." )

                    $fileType = filetype( $pathToDirectory . $aFile );
                    if ( $fileType != "file" && $fileType != "dir")

                    // Get attributes and store in array
                    $dateCreated = filectime( $pathToDirectory . $aFile );
                    $size = filesize( $pathToDirectory . $aFile );

                    $results [] = new FileData( $pathToDirectory, $aFile, $dateCreated, $size, $fileType );

               closedir( $fileList );

          return $results;

$arr = array();
$pathToStartAt = "/path/to/folder";

// Gather data
searchDir($pathToStartAt, $arr);

// Sort into sequence
uasort( $arr, array( 'Filedata','FileCompareSort') );

// Display as a simple list
foreach( $arr as $aFile )  {
     $isDir = ( $aFile->folderSort == 0 ) ? "/" : "";
     echo $aFile->filePath . " " . date("m/d/Y", $aFile->fileDate ) . " " . $aFile->size . " " . $isDir.$aFile->fileName . "<br/>";


Open in new window


Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Echo images using file system 2 33
Php pie charts 3 26
Bootstrap collapse causes odd behavior with php loop 7 24
javascript date picker in php while loop 5 28
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

867 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now