📲 Download Our Apps

EMI Calculator

Download EMI Calculator

SOA Games

Download SOA Games

SOA Technology App

Download SOA Technology

BMI Checker

Download BMI Checker

Task Jira

Download Task Jira

Laughing Adda

Download Laughing Adda

📅 हिंदी कैलेंडर ऐप डाउनलोड करें

Download Shubhcalendar App

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

AI Spiritual Tools & Interactive Experiences

Explore powerful AI-driven tools for daily guidance, spirituality, fun quizzes, and self-discovery.

Today’s Quote

Get inspiring daily quotes powered by AI to motivate and guide your day.

Explore Now

AI Tarot Card Reader

Reveal insights about your future, love, and career with AI tarot readings.

Read Tarot

Love Match Calculator

Check compatibility and love predictions using AI-based analysis.

Check Match

Fortune Cookie

Open an AI fortune cookie and receive wisdom, luck, and fun messages.

Open Cookie

Quiz Categories

Engage with knowledge-based and fun quizzes across multiple categories.

Start Quiz

Panchang Calendar

View daily Panchang, auspicious timings, tithi, nakshatra, and festivals.

View Panchang

Online Numerology

Discover your destiny number, life path, and numerology predictions.

Calculate Now

Spiritual Feeds

Stay connected with spiritual thoughts, mantras, and divine content.

View Feeds

Quiz Hub

Attempt trending quizzes on GK, spirituality, festivals, and more.

Explore Quizzes