PHP 5 – Sort by Folder

Recently, I needed to display a list of files with PHP. My only caveat was that I wanted to do so using newer methods of PHP 5 where possible.

I was delighted to find scandir. Problem was, scandir returns files mixed with folders and that would upset my flock of easily frightened Windows users.

So a quick… er medium… ok fine,  an exasperating search on Google and only outdated, complex and inefficient samples were to be found. PUFF!

So, here is the version I came up with.

Demo

Downloads

How it works

The most crucial part of all the code you will see inside the demo is the PHP getObjects() function. Without this everything else would be moot so lets go over it in a bit more detail.

function getObjects($path) {
    $path .= '/';
    $array = scandir($path); // returns an array of files and folders sorted alphabetically
    $array = array_diff($array, array('.', '..', '.DS_Store', 'Thumbs.db')); // filter out things we don't want

    $return_array = array();

    foreach($array as $item) {
        if(is_dir($path . $item)) {
            $return_array[$item] = getObjects($path . '/' . $item);
        }
    }

    $count = 0;
    foreach($array as $item) {
        if(!is_dir($path . $item)) {
            $return_array[$item] = $item;
            $count++;
        }
    }
    if($count == 0) {
        $return_array[''] = '';
    }

    return $return_array;
}

Line 3
Scandir returns an array of mixed folders and files for the path requested. This does not include sub directories.

Line 4
Filter out any undesirables. That means the current ‘.’ and parent directory ‘..’ although we don’t want any Mac ‘.DS_Store’ or WIndows ‘Thumbs.db’ files either.

Line 6
We create a new array called $return_array which will be built up with all the folders and files in the order we want them. Folders first, then files. Both alphabetically.

Line 8-12
Here we loop through each item in our filtered results from scandir. If the item is a directory we set the results of $return_array[$item] to a recursive call of the very same function we are already in. Traveling deeper each recursive call, that means we can handle seemingly infinite directory structures. Neat.

This first loop through only cares about directories which is exactly what puts them first in our $return_array. Files will come next.

Line 14
We set a variable $count to 0 to keep track of how many files we find in the next foreach loop.

Line 15-19
In this second loop we check to make sure the items are not directories and if so return those items while incrementing the $count variable.

Line 21-23
Now that we are finished looping for files we can check our $count variable. If 0 then set $return_array to ”. This can useful later in case we want to do something special for directories without files.

Line 25
Finally, we return whatever we have found. In most cases this means returning an $array to another instance of the function although ultimately the original one will return a completed array to the PHP call outside our function that started it all.

In the demo we can now loop through this nicely ordered array and write out some HTML and CSS, add a sprinkle of JavaScript and we have a real working web app.

Epilogue

Once you get your head around recursive loops things become much simpler. Plus you get to worry more about optimizing your code since each loop can be run so many times. It’s a good problem to have, really.

Anyway, I certainly hope this helps you in your next endeavor. I know I certainly would be lost without all the wonderful code and tutorials shared by others.

Cheers!


Leaving World of Warcraft

I enjoy obsession. It heightens the experience, unlocks edge abilities and provides clarity of purpose. Like any state, it can be taken too far but with understanding it can be transformed from affliction to strength.

I started World of Warcraft in the beta, many years ago. Before that the strategy games and in one particular modem game even told my future wife I loved her for the first time. Warcraft as you see is very much a part of my history.

The game totally catered to my personality. Obsession with game mechanics, leveling, gearing up and endless side goals took their toll. With increasing focus came new levels of things to tweak, endless rewards for a brain that liked certain buttons pushed.

Even worse that the addiction to the game was the reliance on the game in order to socialize with my friends. It didn’t matter if I got bored of the game, how could I leave my friends? So I would stay a bit longer… maybe it would get better.

But it didn’t. My level of obsession meant overplaying and burning out. It happened many times. Enough that people would joke, “oh, when are you coming back” and “oh, when are you leaving again”.

The problem with “quitting” WoW was that I wasn’t. I was postponing, delaying and pausing. Like a reformed drunk who still keeps his liquor cabinet stocked, secured with the flimsiest of locks. Always there… waiting for that tiny moment of failure.

So after a time, I would feel good again. I could try World of Warcraft again but this time I’d be reasonable. Maybe only an hour a day.

A month later and I’d be raiding, grinding, dying in real life while my avatars gained everything. Seven to eight hours a day and more on the weekends. A horrible cycle I was deathly aware of yet powerless to break out of.

I’d improved so many aspect of my life. A tireless optimizer born from a dysfunctional past. Why couldn’t I break free of WoW? I had made such wonderful gains during my frequent excursions. I wanted to do more, so much more.

The revelation that followed was completely devastating.

After recovering from the initial concept everything became clear. A proper conclusion to WoW. The ending I never had before. Such a simple gesture would set me free.

Getting my virtual affairs in order was a calming. A wonderful time to reflect on all I had done. Soon after, I made sure everyone knew my plans. I would be deleting all my characters. I would not be coming back to World of Warcraft. Reactions were, as you might expect, mixed.

Some people were supportive, others baffled and a few were oddly quiet. I recognize the last state as a valid tactic for dealing with pain so no hard feelings.

It became an event. Come raid with Poof one last time. Come PvP with Foof to celebrate our time together. Come take a screenshot and say goodbye. It was a lovely time of talking, merriment and a celebration of adventures together.

Each one of my characters received their own special ending. Each one a part of my personality and deserving of their own finale. Screenshots of these moments bring me great joy when I reminisce.

Looking back no longer evokes a time wasted, it conjures pleasant memories, shared experiences and pride for all the people I met. So many things we did and so many good times we had.

Looking forward, my gaming experiences do not weaken like I had feared. In fact, they strengthen me.

When you see me coming, I could be Poof the Druid, Foof the Warrior, Old Snake, Commander Shepard or any number of personas that are part of me.

I am a hero, I always was and now that I know, I always will be.

Sincerely,

Poof · Foof · Soof · Daniel · Odn · Shepard · Spock · Sgt Dildo · ForestMist · Neptuna · Old Snake


Leaving World of Warcraft ~ Prelude

One of the pleasures of maturing is an increased awareness of self.

Relaxation, meditation, life experience and even strenuous physical exercise all garner more understanding. Through them you’ll learn your strengths, weaknesses and core desires. After that, a calming sense of self which aids you in all your tasks.

Gains are usually incremental but occasionally something spectacular will happen.


Poof lay still, the springy couch pushing back up against his rather long body. His mind was drifting quite pleasurably, thoughts flowing fast, free and without judgement. An addictive state which he was well aware of enjoying.

The pace did seem to be accelerating though. “Ah, well“, he thought. The all consuming mental fire that could come next was also enjoyable even though it would leave him consumed and tired.

Something was wrong though and in a blinding flash… a revelation. Too clear to unsee, too simple to deny, all at once beautiful and abhorred.

No!” he gasped as his torso shot up from the couch. He couldn’t breathe. Time seemed to drag on then after a short eternity…  a breath… then another.

Normality slowly, painfully returned as he spat “no” several more times. Each utterance with less venom than the last. It seemed to satiate him. A last act of rebellion against destiny revealed.

He knew that to have a chance, a real chance at life he would have to set in motion the unthinkable.

Poof must die” he said with the gravitas of a thousand Sean Connerys.