View Full Version : Get last folder in directory

10-21-2012, 12:17 AM

Okay, i've gone through many attempts and I can't seen to get this to work.
What I'm trying to do is go into a folder and get the LAST folder in there. Then increment that value by one. I can't get it to work. Here is my code.

$path = '../campaigns/';
$results = scandir($path);

foreach ($results as $result) {
if ($result === '.' or $result === '..') continue;

if (is_dir($path . '/' . $result)) {
//code to use if directory

I way to do this is somehow put all the results into one string, then get the last character of the string.. how can that be done?

EDIT: Found an easier solution!

$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);
echo $endfolder;

10-21-2012, 11:13 AM
Here's another solution:

# 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());

echo end($cleanArr);

Note: this will only get the last dir.