Count all resulting values outside foreach loop - php

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.

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>";

<?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>";
?>

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).";

Related

How to store all result from a loop and each result separated by a comma?

Currently I have this working PHP code for search photos inside a folder by name:
$dirname = "photos";
$filenames = glob("$dirname/*{380,381,382,383,384,385}*", GLOB_BRACE);
foreach ($filenames as $filename) {
echo $filename . "<br>";
}
I have typed manualy those numbers 380,381,382,383,384,385 and I would like to have them typed exactly the same but automatically.
If I'm not wrong we have to do an array() on this code:
$start = 380;
$end = 385;
for($i = $start; $i <= $end; $i++) {
echo "$i<br>";
}
I haven't found how to store the whole loop inside a variable for reproduce the same result as the first code but automatically.
$array = range(380, 385);
$string = '{' . implode(',', $array) . '}';
This should work for you:
Just use range() to create the array with the numbers, which you then can implode() into a string, e.g.
$filenames = glob("$dirname/*{" . implode(",", range(308, 385)) . "}*", GLOB_BRACE);

How to loop a directory of text files and echo the wordcount of each file in PHP?

I want to loop through a directory of text files and echo the word count of each file. For example, if the directory contained two text files with the following contents:
file1.txt -> this is file1.
file2.txt -> this is another file called file2.
Then the output should be:
wordcount: 3
wordcount: 6
I have the following code:
$directory = "C:\\dir";
$files = scandir($directory);
foreach($files as $file) {
$fh = fopen($file, "r");
$contents = fread($fh, filesize($file));
fclose($fh);
echo "wordcount: "; //this should be modified to display the wordcount for each file..
}
The echo should be modified to echo the wordcount for each file..
This should work for you:
$directory = "C:\\xampp\\htdocs\\Sandbox";
foreach (glob("$directory\\*.txt") as $file) {
$fh = fopen($file, "r");
if(filesize($file) > 0) {
$contents = fread($fh, filesize($file));
$count = str_word_count($contents, 0);
} else {
$count = 0;
}
fclose($fh);
echo "File: " . basename($file) . " Wordcount: $count<br />";
}
A output could look like this:
File: test - Kopie (2).txt Wordcount: 3
File: test - Kopie.txt Wordcount: 2
File: test.txt Wordcount: 7
<?php
$directory = "/var/www/stackoverflow/jql"; //My directory , change it to yours
$files = scandir($directory);
foreach($files as $file) {
$fh = fopen($file, "r");
$contents = fread($fh, filesize($file));
$contents2 = ereg_replace('[[:space:]]+', '', $contents);
$numChar = strlen($contents2);
echo "The $file have ". $numChar . " Words count <br>";
}
Outputs :
The jql.js have 964 Words count
The my.svg have 71721 Words count
The test.csv have 60 Words count
Simple code:
$files = scandir('dir_name/');
foreach ($files as $file) { $str = file_get_contents('dir_name/'.$file);echo $file .'-'.str_word_count($str, 0);}
<?php
$wordFrequencyArray = array();
function countWords($file) use($wordFrequencyArray) {
/* get content of $filename in $content */
$content = strtolower(file_get_contents($filename));
/* split $content into array of substrings of $content i.e wordwise */
$wordArray = preg_split('/[^a-z]/', $content, -1, PREG_SPLIT_NO_EMPTY);
/* "stop words", filter them */
$filteredArray = array_filter($wordArray, function($x){
return !preg_match("/^(.|a|an|and|the|this|at|in|or|of|is|for|to)$/",$x);
});
/* get associative array of values from $filteredArray as keys and their frequency count as value */
foreach (array_count_values($filteredArray) as $word => $count) {
if (!isset($wordFrequencyArray[$word])) $wordFrequencyArray[$word] = 0;
$wordFrequencyArray[$word] += $count;
}
}
$filenames = array('file1.txt', 'file2.txt', 'file3.txt', 'file4.txt' ...);
foreach ($filenames as $file) {
countWords($file);
}
print_r($wordFrequencyArray);

Scandir newest files in array with limit

I have made a PHP script to scan a directory, it lists all filenames in an array with a limit of 20. Now its displaying only the beginning of the array. So if there are 40 files, it displays only the first 0-20 but we need 20-40.. Can someone help me ? Thanks!!
<?php
$files = glob('data/*.{png}', GLOB_BRACE);
usort($files, 'filemtime_compare');
function filemtime_compare($a, $b)
{
return filemtime($a) - filemtime($b);
}
$i = 0;
$show = 20;
foreach($files as $file)
{
if($i == $show) {
break;
} else {
++$i;
}
$var .= $file . "\n";
}
$fp = fopen("data.txt", "wb");
fwrite($fp, $var);
fclose($fp);
echo $var;
?>
You could use array_chunk() to split the $files array up in chunks of 20 files. Then use implode() to format the values in a chunk to a single string. Replace the foreach loop with this:
$show = 20;
$files = array_chunk($files, $show);
$page = 0; // page 0 is 0-19, page 1 is 20-39, etc.
$var = implode("\n", $files[$page]);
Edit: For the last 20 files you could use array_slice():
$files = array_slice($files, -20);
$var = implode("\n", $files);

Read line for first top 10 lines and display word in each line of 10 lines using PHP

I have the PHP code as below:
<?php
$path = "files/stats_pmta.affinitead.net.2012-12-12.txt";
$num = 10;
$fh = #fopen($path, 'r');
if ($fh){
for ($i=0;$i<$num;$i++){
$newfile = fgets($fh,1024);
$t = explode(";", $newfile);
echo $t;
echo "<br>";
}
} else {
echo 1;
}
?>
I want to read all data in file stats_pmta.affinitead.net.2012-12-12.txt that read only first 10 lines of the file below:
2012-12-12-0551;affinitead.net;1221588;106346;8.70;gmail.com;123577;7780;6.29
2012-12-12-0551;affinitead.net;1221588;106346;8.70;wanadoo.fr;123562;9227;7.46
2012-12-12-0551;affinitead.net;1221588;106346;8.70;yahoo.fr;104819;1685;1.60
2012-12-12-0551;affinitead.net;1221588;106346;8.70;orange.fr;87132;7341;8.42
2012-12-12-0551;affinitead.net;1221588;106346;8.70;laposte.net;79597;1040;1.30
2012-12-12-0551;affinitead.net;1221588;106346;8.70;hotmail.fr;77601;14107;18.17
2012-12-12-0551;affinitead.net;1221588;106346;8.70;neuf.fr;67392;1793;2.66
2012-12-12-0551;affinitead.net;1221588;106346;8.70;hotmail.com;55300;10494;18.97
2012-12-12-0551;affinitead.net;1221588;106346;8.70;free.fr;43422;1706;3.92
2012-12-12-0551;affinitead.net;1221588;106346;8.70;sfr.fr;39063;251;.64
2012-12-12-0551;affinitead.net;1221588;106346;8.70;aol.com;32061;9859;30.75
2012-12-12-0551;affinitead.net;1221588;106346;8.70;club-internet.fr;22424;233;1.03
2012-12-12-0551;affinitead.net;1221588;106346;8.70;yahoo.com;18646;1365;7.32
2012-12-12-0551;affinitead.net;1221588;106346;8.70;voila.fr;18513;3650
After I read first top 10 lines I want to display the word in each line like:
2012-12-12-0551;affinitead.net;1221588;106346;8.70;gmail.com;123577;7780;6.29
I want to display gmail.com 123577 7780 6.29
But PHP code above I just got the output array.I don't know how to fix this.Anyone help me please , Thanks.
You could do something like this:
$path = 'path/to/file'
$fp = fopen($path, 'r');
$count = 0;
while($columns = fgetcsv($fp, 256, ';', '"')
{
if(++$count > 10)
break;
echo implode("\t", $colums);
}
If you don't know, how implode works, look here: http://de1.php.net/manual/de/function.implode.php
This is a way you could do it by using the PHP-function explode.
$textFile = file_get_contents("test.txt");
$lineFromText = explode("\n", $textFile);
$row = 0;
foreach($lineFromText as $line)
{
if($row <= 10)
{
$words = explode(";",$line);
echo $words[5] . ' ' . $words[6] . ' ' . $words[7] . ' ' . $words[8];
$row++;
}
}
Edited the code so that you can replace your own, you might want to check if the file is empty e t c before trying to do anyting thou.

Count how many files in directory PHP

I'm working on a slightly new project. I wanted to know how many files are in a certain directory.
<div id="header">
<?php
$dir = opendir('uploads/'); # This is the directory it will count from
$i = 0; # Integer starts at 0 before counting
# While false is not equal to the filedirectory
while (false !== ($file = readdir($dir))) {
if (!in_array($file, array('.', '..') and !is_dir($file)) $i++;
}
echo "There were $i files"; # Prints out how many were in the directory
?>
</div>
This is what I have so far (from searching). However, it is not appearing properly? I have added a few notes so feel free to remove them, they are just so I can understand it as best as I can.
If you require some more information or feel as if I haven't described this enough please feel free to state so.
You can simply do the following :
$fi = new FilesystemIterator(__DIR__, FilesystemIterator::SKIP_DOTS);
printf("There were %d Files", iterator_count($fi));
You can get the filecount like so:
$directory = "/path/to/dir/";
$filecount = count(glob($directory . "*"));
echo "There were $filecount files";
where the "*" is you can change that to a specific filetype if you want like "*.jpg" or you could do multiple filetypes like this:
glob($directory . "*.{jpg,png,gif}",GLOB_BRACE)
the GLOB_BRACE flag expands {a,b,c} to match 'a', 'b', or 'c'
Note that glob() skips Linux hidden files, or all files whose names are starting from a dot, i.e. .htaccess.
Try this.
// Directory
$directory = "/dir";
// Returns an array of files
$files = scandir($directory);
// Count the number of files and store them inside the variable..
// Removing 2 because we do not count '.' and '..'.
$num_files = count($files)-2;
You should have :
<div id="header">
<?php
// integer starts at 0 before counting
$i = 0;
$dir = 'uploads/';
if ($handle = opendir($dir)) {
while (($file = readdir($handle)) !== false){
if (!in_array($file, array('.', '..')) && !is_dir($dir.$file))
$i++;
}
}
// prints out how many were in the directory
echo "There were $i files";
?>
</div>
The best answer in my opinion:
$num = count(glob("/exact/path/to/files/" . "*"));
echo $num;
It doesnt counts . and ..
Its a one liner
Im proud of it
Since I needed this too, I was curious as to which alternative was the fastest.
I found that -- if all you want is a file count -- Baba's solution is a lot faster than the others. I was quite surprised.
Try it out for yourself:
<?php
define('MYDIR', '...');
foreach (array(1, 2, 3) as $i)
{
$t = microtime(true);
$count = run($i);
echo "$i: $count (".(microtime(true) - $t)." s)\n";
}
function run ($n)
{
$func = "countFiles$n";
$x = 0;
for ($f = 0; $f < 5000; $f++)
$x = $func();
return $x;
}
function countFiles1 ()
{
$dir = opendir(MYDIR);
$c = 0;
while (($file = readdir($dir)) !== false)
if (!in_array($file, array('.', '..')))
$c++;
closedir($dir);
return $c;
}
function countFiles2 ()
{
chdir(MYDIR);
return count(glob("*"));
}
function countFiles3 () // Fastest method
{
$f = new FilesystemIterator(MYDIR, FilesystemIterator::SKIP_DOTS);
return iterator_count($f);
}
?>
Test run: (obviously, glob() doesn't count dot-files)
1: 99 (0.4815571308136 s)
2: 98 (0.96104407310486 s)
3: 99 (0.26513481140137 s)
Working Demo
<?php
$directory = "../images/team/harry/"; // dir location
if (glob($directory . "*.*") != false)
{
$filecount = count(glob($directory . "*.*"));
echo $filecount;
}
else
{
echo 0;
}
?>
I use this:
count(glob("yourdir/*",GLOB_BRACE))
<?php echo(count(array_slice(scandir($directory),2))); ?>
array_slice works similary like substr function, only it works with arrays.
For example, this would chop out first two array keys from array:
$key_zero_one = array_slice($someArray, 0, 2);
And if You ommit the first parameter, like in first example, array will not contain first two key/value pairs *('.' and '..').
Based on the accepted answer, here is a way to count all files in a directory RECURSIVELY:
iterator_count(
new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator('/your/directory/here/', \FilesystemIterator::SKIP_DOTS)
)
)
$it = new filesystemiterator(dirname("Enter directory here"));
printf("There were %d Files", iterator_count($it));
echo("<br/>");
foreach ($it as $fileinfo) {
echo $fileinfo->getFilename() . "<br/>\n";
}
This should work
enter the directory in dirname. and let the magic happen.
Maybe usefull to someone. On a Windows system, you can let Windows do the job by calling the dir-command. I use an absolute path, like E:/mydir/mysubdir.
<?php
$mydir='E:/mydir/mysubdir';
$dir=str_replace('/','\\',$mydir);
$total = exec('dir '.$dir.' /b/a-d | find /v /c "::"');
$files = glob('uploads/*');
$count = 0;
$totalCount = 0;
$subFileCount = 0;
foreach ($files as $file)
{
global $count, $totalCount;
if(is_dir($file))
{
$totalCount += getFileCount($file);
}
if(is_file($file))
{
$count++;
}
}
function getFileCount($dir)
{
global $subFileCount;
if(is_dir($dir))
{
$subfiles = glob($dir.'/*');
if(count($subfiles))
{
foreach ($subfiles as $file)
{
getFileCount($file);
}
}
}
if(is_file($dir))
{
$subFileCount++;
}
return $subFileCount;
}
$totalFilesCount = $count + $totalCount;
echo 'Total Files Count ' . $totalFilesCount;
Here's a PHP Linux function that's considerably fast. A bit dirty, but it gets the job done!
$dir - path to directory
$type - f, d or false (by default)
f - returns only files count
d - returns only folders count
false - returns total files and folders count
function folderfiles($dir, $type=false) {
$f = escapeshellarg($dir);
if($type == 'f') {
$io = popen ( '/usr/bin/find ' . $f . ' -type f | wc -l', 'r' );
} elseif($type == 'd') {
$io = popen ( '/usr/bin/find ' . $f . ' -type d | wc -l', 'r' );
} else {
$io = popen ( '/usr/bin/find ' . $f . ' | wc -l', 'r' );
}
$size = fgets ( $io, 4096);
pclose ( $io );
return $size;
}
You can tweak to fit your needs.
Please note that this will not work on Windows.
simple code add for file .php then your folder which number of file to count its
$directory = "images/icons";
$files = scandir($directory);
for($i = 0 ; $i < count($files) ; $i++){
if($files[$i] !='.' && $files[$i] !='..')
{ echo $files[$i]; echo "<br>";
$file_new[] = $files[$i];
}
}
echo $num_files = count($file_new);
simple add its done ....

Categories