I would like to count all characters in text files in certain path, so i've wrote the following code
<?PHP
$files = glob('my/files/path/*.txt', GLOB_BRACE);
foreach($files as $file) {
$str = file_get_contents($file) or dir("can not read file");
$numCharSpace = strlen($str);
echo "Counted " .$numCharSpace. " character(s).<br>";
}
?>
Let say, we have 4 files inside this path so it will print out the following
Counted 201 character(s).
Counted 99 character(s).
Counted 88 character(s).
Counted 112 character(s).
How can i get the total of all which should be 500 character(s)
so how to print out the count of all results which are inside foreach();
loop.
With strlen
you get the number of the bytes of the file. So, you can as well get that directly, without the need to read the file contents.
$numberOfChars = array_sum(
array_map('filesize', glob('my/files/path/*.txt', GLOB_BRACE))
);
What this does is get the file size for each one of the files returned by glob
, and sum them using array_sum
.
<?PHP
$files = glob('my/files/path/*.txt', GLOB_BRACE);
$Total = 0;
foreach($files as $file) {
$str = file_get_contents($file) or dir("can not read file");
$numCharSpace = strlen($str);
echo "Counted " .$numCharSpace. " character(s).<br>";
$Total += $numCharSpace;
}
echo "Total " .$Total. " characters.<br>";
?>
You can use a variable to sum. Then you could use filesize()
to get total bytes of the file instead of load it:
$files = glob('my/files/path/*.txt', GLOB_BRACE);
$total = 0;
foreach($files as $file) {
$numCharSpace = filesize($file);
$total += $numCharSpace ;
}
echo "Counted " .$total. " character(s).<br>";
Following code should work :
$files = glob('my/files/path/*.txt', GLOB_BRACE);
$numCharSpace = 0;
foreach($files as $file) {
$str = file_get_contents($file) or dir("can not read file");
$numCharSpace = $numCharSpace + strlen($str);
}
echo "Counted " .$numCharSpace. " character(s).
";