View Full Version : Get last folder in directory array

10-21-2012, 09:53 PM
This code will go into a directory on your website and get all the folders in that directory, and put them into an array.

$folder = array(); // Creates a array for use later

foreach (glob("*") as $thefolder) { // Use for each to go through and get each folder & file in the given directory
If (is_dir($thefolder)) { // We only want to get folders so we are making sure that we are adding a directory and not a file.
$folder[] = $thefolder; // Adds the file to the array created
$endfolder = end($folder); //Last folder
$endfolder now contains the Last folder in the directory.

Solution 2 (Credit to bjarneo):

# Create a new DirectoryIterator object with the path you want to iterate through
$dir = new DirectoryIterator('/wamp/www/cf');

# Clean array
$cleanArr = array();

# Iterate through all directories,
# and as long as they're not '.' or '..'(isDot), put them in array.
foreach($dir as $item) {
if($item->isDir() && !$item->isDot()) {
$cleanArr[] = htmlentities($item->getPathname());

$lastfolder = end($cleanArr);
$lastfolder now contains the last folder in the array.