0

I have one CSV file. It contains 3 columns I want to count only the 3rd column total rows. I tried with one code but It showed the whole CSV file rows counts.

$record = file('filename.csv', FILE_IGNORE_NEW_LINES |  FILE_SKIP_EMPTY_LINES);
$total_record = count($record);
echo  $total_record; // output 6

As per the below image, I want to count only the Ph_no column. Please help me out

enter image description here

2
  • Use the CSV library. php.net/manual/en/function.fgetcsv.php. Also do you expect to count the header line, and the empty lines? Commented Dec 9, 2021 at 17:41
  • Well thats because you are counting the number of occurances in the array created from the file() Commented Dec 9, 2021 at 17:41

3 Answers 3

1

You could use array_map() to run callback str_getcsv() on each element (row) in the array that is returned by file().

$arr = array_map('str_getcsv', file('./filename.csv'));

The result ($arr) would look something like this:

Array
(
    [0] => Array
        (
            [0] => First_Name
            [1] => Last_name
            [2] => Ph_no
        )

    [1] => Array
        (
            [0] => ABC
            [1] => AB
            [2] => 1234567890
        )

    ... etc.

You can then count the number of phone numbers:

$phNo = array_column($arr, 2);
$phNoCount = count($phNo) -1 ; // subtract the header
echo 'Ph_no count: ' . $phNoCount;
Sign up to request clarification or add additional context in comments.

3 Comments

I tried with your code, working fine actually but It's counting blank rows too. I need to skip empty rows while counting phone number column
change: $phNo = array_column($arr, 2); to $phNo = array_filter(array_column($arr, 2)); // remove empty cells
Thank a lot It's working fine now
0
$file = fopen('myCSVFile.csv', 'r');
$count = 0;
while (($line = fgetcsv($file)) !== FALSE) {
    $num = count($line);
    for ($i=0; $i < $num; $i++) {
        if(!empty($line[2]) {
            $count++;
        }
    }
}
fclose($file);
echo $count;

1 Comment

Your code is not working for me please help me once
0

Using the fgetcsv() function it is quite simple

$tot = 0;
if (($f = fopen("filename.csv", "r")) !== FALSE) {
    // read and ignore first line, titles
    fgetcsv($f, 1000, ",");
    while (($line = fgetcsv($f, 1000, ",")) !== FALSE) {
        if ( $line[2] !== '' ) {
            $tot += $line[2];   // accumulate column 3
        }
    }
}
fclose($f);
echo $tot;

1 Comment

I tried with your Code but the output I'm getting 0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.