1

I have a directory of ever-changing CSV files that I wish to read and count the number of times a word appears in a certain "column." I'm using the following code to do it successfully with a single file:

$file = 'Some\Random\Directory\myfile.txt');

$fh = fopen($file, 'rb');

$tag = array();

while($col = fgetcsv($fh)) {
    if (isset($tag[$col[2]])) {
       $tag[$col[2]]++;
    } else {
       $tag[$col[2]] = 1;
    }
}
fclose($fh);

$foo = ($tag['foo']);
$bar = ($tag['bar']);
echo $foo;

But, I have gotten hung up when attempting to parse the entire directory with this code:

$files = glob('Some\Random\Directory\*.txt');
foreach($files as $file){
    $fh = fopen($file, 'rb');

    $tag = array();

    while($col = fgetcsv($fh)) {

        if (isset($tag[$col[2]])) {
            $tag[$col[2]]++;
        } else {
            $tag[$col[2]] = 1;
        }
    }
    fclose($fh);

    $foo = ($tag['foo']);
    $bar = ($tag['bar']);
    $foo_sum = array_sum($foo);    
}
echo $foo_sum;

This code results in nothing being shown on the page. If I remove the array_sum() function and place the echo inside the loop, all of the instances of foo are displayed, but as one number per file. What is keeping me from obtaining the sum of all the foos?

2 Answers 2

1

You reset your array every time you loop. Pull it before your loop and evaluate it afterwards

$tag = array();
$files = ...;
foreach (...) {
...
}

$foo = ($tag['foo']);
$bar = ($tag['bar']);
$foo_sum = array_sum($foo);    
echo $foo_sum;

If you just need the count of foos, you can also do

echo $tag['foo'];

No need for array_sum(), since there will be only one $tag['foo'].

Sign up to request clarification or add additional context in comments.

Comments

0

try $foo_sum += array_sum($foo);. You are overwriting the value every time you loop.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.