Hi,

I need help with writing a piece of code that counts all the folders in a specific directory and prints the number, then counts image files in the same directory but located in all the fullsize sub folder of each gallery.

Example:

-images
-galleries
-gallery1
- fullsize
-thumbs
-gallery2
- fullsize
-thumbs
-gallery3
- fullsize
-thumbs

and so forth.

So far I have this much of the code:

<?php


$directory='images/galleries';


$count=0;


if ($handle = opendir($directory)) {
    ;

    
    while (false !== ($file = readdir($handle))) {
        ;

        
        $file_parts=explode('.',$file);
        $file_parts_counts=count($file_parts);
        $file_type_location=$file_parts_counts-1;
        $file_type=$file_parts[$file_type_location];
        
        
        $count=$count+1;

    }

    closedir($handle);
}
echo "Galleries: <b>$count</b>";
?>

There are 31 folders in the gallery folder and count returns 39.

Can someone please shed some light here.

Thank you very much.

Hi,

I need help with writing a piece of code that counts all the folders in a specific directory and prints the number, then counts image files in the same directory but located in all the fullsize sub folder of each gallery.

Example:

-images
-galleries
-gallery1
- fullsize
-thumbs
-gallery2
- fullsize
-thumbs
-gallery3
- fullsize
-thumbs

and so forth.

So far I have this much of the code:

<?php


$directory='images/galleries';


$count=0;


if ($handle = opendir($directory)) {
    ;

    
    while (false !== ($file = readdir($handle))) {
        ;

        
        $file_parts=explode('.',$file);
        $file_parts_counts=count($file_parts);
        $file_type_location=$file_parts_counts-1;
        $file_type=$file_parts[$file_type_location];
        
        
        $count=$count+1;

    }

    closedir($handle);
}
echo "Galleries: <b>$count</b>";
?>

There are 31 folders in the gallery folder and count returns 39.

Can someone please shed some light here.

Thank you very much.

You're counting the "images" folder as well. Each directory will have a . directory in it that points to the parent directory.

So you're counting the parent directory when you count the ".".

You probably want.

while (false !== ($file = readdir($handle))) {
        ;

        if ($file == '.' || $file == '..') {
          continue; // skip this file
        }
        
        $file_parts=explode('.',$file);
        $file_parts_counts=count($file_parts);
        $file_type_location=$file_parts_counts-1;
        $file_type=$file_parts[$file_type_location];
        
        
        $count=$count+1;

    }

Also to get the file extension on one line:

$file_type = substr($file, strrpos($file, '.')+1);

You can also abbreviate:

$count=$count+1;

to:

$count++;
This article has been dead for over six months. Start a new discussion instead.