how to get occurrences of specific column in csv file in php

You can easily get the occurrences (frequency count) of values from a specific column in a CSV file using PHP’s built-in functions. Here’s a step-by-step example:

Example: Count occurrences of values in a specific column of CSV

Suppose you have a CSV file like this (data.csv):

id,name,city
1,Aditya,Delhi
2,Ravi,Mumbai
3,Neha,Delhi
4,Amit,Bangalore
5,Raj,Delhi
6,Simran,Mumbai

And you want to count how many times each city appears.


PHP Code:

<?php
$file = "data.csv";
$columnIndex = 2; // Column index (0 = first column, 1 = second, 2 = third ...)

$counts = [];

if (($handle = fopen($file, "r")) !== FALSE) {
    $header = fgetcsv($handle); // Skip header row
    while (($data = fgetcsv($handle)) !== FALSE) {
        $value = $data[$columnIndex];
        if (!empty($value)) {
            if (!isset($counts[$value])) {
                $counts[$value] = 0;
            }
            $counts[$value]++;
        }
    }
    fclose($handle);
}

print_r($counts);

Output:

Array
(
    [Delhi] => 3
    [Mumbai] => 2
    [Bangalore] => 1
)

Explanation:

We count occurrences in an associative array $counts.

fopen opens the CSV file.

fgetcsv reads each row as an array.

$columnIndex tells which column you want to analyze.




Leave a Reply