简体   繁体   中英

Size of files of a scanned directory - PHP

I want to read a directory and get the filesize of each file. I tried the following code:

$downloads = array_slice(scandir("downloads"),2);
$size = array();
foreach($downloads as $value) {
    $size = filesize("downloads/".$value);
    echo($size); //at this point the echo works correctly
}
echo($size); //shows the filesize of the first file
echo($size[1]) //nothing happens
foreach($size as $value) {
    echo($value); //nothing happens
    echo($size); //nothing happens
}

That's why I'm quiet confused about the work with arrays and loops right now. It would also be nice to save the filenames and their corresponding filesizes in one array.

Thanks for your suggestions.

You're doing it wrong. You're overriding the array in the foreach.

foreach($downloads as $value) {
    $size = filesize("downloads/".$value);
    // $size is not an array anymore, just an int
    echo($size); //at this point the echo works correctly
}

This should be correct:

foreach($downloads as $value) {
    $size[] = filesize("downloads/".$value);
}

Full code:

$downloads = array_slice(scandir("downloads"),2);
$size = array();

foreach($downloads as $value) {
    $size[] = filesize("downloads/".$value);
}

foreach($size as $value) {
    echo($value).'<br/>';
}

You are constantly overwriting the $size variable, that's why it is not carried on with each foreach execution.

You should create a $size array and store everything accordingly:

$size = array();
foreach ( $downloads as $file ) {
    $size["downloads/".$file] = filesize("downloads/".$file);
}

foreach ( $size as $fname => $fsize) {
    echo "Size of " .$fname. " is " .$fsize. " bytes.";
}

When you assign the value:

foreach($downloads as $value) {
$size = filesize("downloads/".$value);
echo($size); //at this point the echo works correctly
}

you need to add it to a specific record of 'size' as

$size[ $n ] = filesize( ... );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM