Dryden Long
Dryden Long

Reputation: 10182

Count number of similar values in CSV column

I have several .csv files that I am trying to loop through and read the values of a specific column as well as count how often each value appears. For example, the third column in one of the files, we'll call it $col[2], looks like this:

HEADER
foo
bar
bar
bar
foo

I can count the number of times both foo and bar appear in the file using this code:

$file = ('Path/To/Random/File.txt');

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

$tag = array();
while($col = fgetcsv($fh)) {
    $tag[$col[2]]++;
}

print_r($tag);

Result:

5

But, this code returns the count for all of the values in col[2] . How can I specify that I want the number of foo and bar values, only split into which count belongs to which value? For example, the result would look something like this:

echo $foo_count;
echo $bar_count;

Result:

2
3

Upvotes: 2

Views: 2002

Answers (1)

Gabriel Sosa
Gabriel Sosa

Reputation: 7956

I would do:

$file = ('Path/To/Random/File.txt');

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

$tag = array();
while($col = fgetcsv($fh)) {

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

be sure $col[2] actually contains the value you want to measure/iterate

once that you should have an array like, use print_r to check

'foo' => 2,
'bar' => 3

Upvotes: 2

Related Questions