Skip to content
PHP Logo

What are the differences between using `array_reduce()` and `foreach()` loops in PHP to calculate the total size of files in a directory?

When calculating the total size of files in a directory in PHP, using `array_reduce()` can be more concise and efficient compared to using a `foreach()` loop. `array_reduce()` allows you to reduce an array to a single value by iteratively applying a callback function, which is ideal for summing up file sizes. On the other hand, `foreach()` loops require more code and manual iteration to achieve the same result.

php
// Using array_reduce() to calculate the total size of files in a directory
$directory = '/path/to/directory';
$files = scandir($directory);
$totalSize = array_reduce($files, function($carry, $file) use ($directory) {
    if ($file != '.' && $file != '..') {
        $carry += filesize($directory . '/' . $file);
    }
    return $carry;
}, 0);

echo "Total size of files in directory: " . $totalSize . " bytes";