Forum Moderators: coopster

Message Too Old, No Replies

Problem counting files in directory

         

denisl

11:24 pm on Jan 14, 2010 (gmt 0)

10+ Year Member Top Contributors Of The Month



I have been trying to count the number of image files in a directory using:

$imgcount = count(glob( "$imagebdir*.jpg"));

It appears to work fine except when ther are no images in the directory, then it returns a count of 1, never zero.

Any ideas?

TheMadScientist

11:42 pm on Jan 14, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Yes, from the manual:

Returns an array containing the matched files/directories, an empty array if no file matched or FALSE on error.

PHP Glob [us2.php.net]

You're essentially getting $imgcount[0]=""; which results in a count of 1.

I'd probably use a conditional:


$countImages=glob("$imagebdir*.jpg");
if(count($countImages)>1 ¦¦ !empty($countImages[0])) {
$imgcount=count($countImages);
}
else {
$imgcount=0;
}

* Make sure to change the broken-bar characters to standard bar characters if copying and pasting.

denisl

8:25 am on Jan 15, 2010 (gmt 0)

10+ Year Member Top Contributors Of The Month



Thank you, that works fine.

I had read that item in the manual but didn't understand how to deal with it.
Strangely, I had searched on the web for "counting files with php" and had found several references to using the glob method with that one line of code but no one dealt with the problem of the false 1.

Thank you again