Jump to content

Count files (readdir or array)


son
 Share

Recommended Posts

I get all files from a directory of photos and display them on a page. The code I use is:

$max_num = 40;$j=0;$narray = array();$dir = "Brighton/full/"; // name of the folder where images are storedif (is_dir($dir)) {   $dh= @opendir($dir) or die("Unable to open $path please notify the administrator. Thank you."); // confirm directories exist   while (($file = readdir($dh)) !== false) {  // read the entire directory   	if (($file != '.') &&  ($file != '..') && (stristr($file,'jpg'))) { //jpg files only   if (file_exists($dir . $file)) {        $narray[]=$file;        $n++;        }        }   }if ($n < $max_num) {	$max_num = $n;  // reset the max_num if not enough pictures	}echo "<ul class=\"slides\">";  while ( $j <= $max_num-1) {

As you have to limit the while loop I use a maximum number, but wondered if there is a way to count the files in directory and then use this number instead. In future the number of image might be different and as this is a friends site who has no knowledge of web technologies it could be a full-time job for me to change the code with each image change in folder... Or could I count the images in array instead?Does anyone know how to do that?Son

Link to comment
Share on other sites

In $narray you are saving paths to all valid files$narray[]=$file;afther that the size of that array would be the number of images in that folder: count($narray)and just loop through that array

for ($i =0; $i < count($narray); $i++){	#do something with $narray}

_edit_here is an easier way to count number of jpeg images on a given folder:

<?php$dir = "Brighton/full/";echo $numberOfImages = count(glob($dir."*.jpg"));?>

Link to comment
Share on other sites

In $narray you are saving paths to all valid files$narray[]=$file;afther that the size of that array would be the number of images in that folder: count($narray)and just loop through that array
for ($i =0; $i < count($narray); $i++){	#do something with $narray}

_edit_here is an easier way to count number of jpeg images on a given folder:

<?php$dir = "Brighton/full/";echo $numberOfImages = count(glob($dir."*.jpg"));?>

Lulzim,Thanks a lot. Does the trick!Son:-)
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...