Count number of files in folder

Asked

Viewed 4,562 times

2

I am creating a listing of images contained inside a folder, but I would like to count the amount of files inside the folder, how do I? Below 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."\">';
}

?>

2 answers

3


As the function glob() 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."\">';
}

  • That’s exactly what I was looking for, thank you very much :D

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 an array/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);
?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.