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
I would do:
be sure
$col[2]actually contains the value you want to measure/iterateonce that you should have an array like, use
print_rto check