olo
olo

Reputation: 5271

count images in folder and print image names

I made a function for counting how many images are in the folder, also I'd like to print images in array. This is a working snippet for counting.

<?php
 function countNum($dir){
 $i = 0;
 $dir_array = scandir($dir);
  foreach($dir_array as $key=>$value){
  if($value!=".." && $value!="."){
   if(is_file($dir."/".$value)){

      $i++;
   }
  }
 }
 return array($i);
}

$num = countNum("images");
echo $num[0];
?>

echo $value; I get all image file names

AAA_1.jpg  AAA_2.jpg  AAA_3.jpg  AAA_4.jpg  BBB_1.jpg  BBB_2.jpg  BBB_3.jpg  BBB_4.jpg

how do I return them as array?

Upvotes: 0

Views: 881

Answers (3)

ChicagoRedSox
ChicagoRedSox

Reputation: 638

If you're really trying to only take image files, where there might be others:

function getImages($dir) {
  //make a list of extensions
  $extensions = [
    'jpg',
    'png',
    'gif',
    //......other image extensions
  ];
  return array_filter(scandir($dir), function ($val) use ($extensions) {
    //get extension from file
    $ext = pathinfo("$dir/$val")['extension'];
    //only include file if extension matches list
    return in_array($ext, $extensions);
  });
}
$files = getImages("images");
//now show what's in there
print_r($files);
echo count($files);

Upvotes: 1

Taj Morton
Taj Morton

Reputation: 1638

Try this:

function getFiles($dir){
     $files = array();
     $dir_array = scandir($dir);
     foreach($dir_array as $key=>$value) {
         if($value!=".." && $value!=".") {
             if(is_file($dir."/".$value)) {
                 $files[]=$value;
             }
          }
     }
     return $files;
}

$all_files = getFiles("images");
$num = count($all_files);
echo "Count: $num\n";
echo $all_files[0];

Upvotes: 2

Andrzej Ośmiałowski
Andrzej Ośmiałowski

Reputation: 1504

Just create an empty array and put an element to this array in your forach loop.

Snippet attached:

$array = array();
foreach ($files as $file) {
  $array[] = $file;
}

Alternatively, you can use array_push() function which does the same job.

Upvotes: 0

Related Questions