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

Got it You want to count occurrences of values in a specific column, but only when a condition on another column is met.


Example CSV (data.csv):

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

Task

Count how many times each city appears, but only where status = ‘active’.


PHP Code:

<?php
$file = "data.csv";
$targetColumn = "city";     // Column we want to count
$conditionColumn = "status"; // Column to apply condition
$conditionValue = "active";  // Condition value

$counts = [];

if (($handle = fopen($file, "r")) !== FALSE) {
    $header = fgetcsv($handle); // Get header row
    
    // Find index of target and condition columns
    $targetIndex = array_search($targetColumn, $header);
    $conditionIndex = array_search($conditionColumn, $header);

    while (($data = fgetcsv($handle)) !== FALSE) {
        if ($data[$conditionIndex] === $conditionValue) {
            $value = $data[$targetIndex];
            if (!empty($value)) {
                if (!isset($counts[$value])) {
                    $counts[$value] = 0;
                }
                $counts[$value]++;
            }
        }
    }
    fclose($handle);
}

print_r($counts);

Output:

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

Explanation:

  • $targetColumn = "city" → the column whose occurrences we want.
  • $conditionColumn = "status" → the column we filter on.
  • $conditionValue = "active" → only count rows where status is active.



Leave a Reply