Count number of files in folder

2

I'm creating a list of images contained within a folder, but I would like to count the amount of files inside the folder, how do I? Here is the code I'm using:

<?php 

$pasta = 'imagens/';
$arquivos = glob("$pasta{*.jpg,*.JPG,*.png,*.gif,*.bmp}", GLOB_BRACE);
foreach($arquivos as $img){
   echo '<img src=\"imagens/".$img."\">';
}

?>
    
asked by anonymous 18.07.2015 / 00:51

2 answers

3

Since the glob() function returns an array, just count the number of indexes with the function count() :     

$pasta = 'imagens/';
$arquivos = glob("$pasta{*.jpg,*.JPG,*.png,*.gif,*.bmp}", GLOB_BRACE);

echo "Total de Imagens" . count($arquivos);

foreach($arquivos as $img){
   echo '<img src=\"imagens/".$img."\">';
}
    
18.07.2015 / 01:01
2

You can increment a variable, like this:

<?php 
$pasta = 'imagens/';
$arquivos = glob("$pasta{*.jpg,*.JPG,*.png,*.gif,*.bmp}", GLOB_BRACE);

$i = 0;

foreach($arquivos as $img){
    echo '<img src=\"imagens/".$img."\">';
    $i++;
}

echo 'Total:', $i;
?>

If you want to get the result before displaying the images, you can use a vector / array

<?php 
$pasta = 'imagens/';
$arquivos = glob("$pasta{*.jpg,*.JPG,*.png,*.gif,*.bmp}", GLOB_BRACE);

$i = 0;
$images = array();

foreach($arquivos as $img){
    $images[] = '<img src=\"imagens/".$img."\">';
    $i++;
}

echo 'Total:', $i;

echo implode(PHP_EOL, $images);
?>
    
18.07.2015 / 00:58