Skip to content
Advertisement

Is it possible to count how many rows have an empty specified ‘cell’ or column in a csv?

I have a changing csv file that looks something like the following. I am trying to find out how I can count how many jobs have not been completed yet (have an empty field) CSV example:

id,job_name,started,completed,
1,project_1,17-07-20,20-07-20,
2,project_2,18-07-20,,
3,project_3,18-07-20,19-07-20,
4,project_4,19-08-20,,
5,project_5,20-07-20,,

In this example, I am looking to return ‘3’. (out of the 6 lines, 3 lines show row 4 as being empty)

This is what I have so far:

<?php

    $csv_complete_contents = array_map('str_getcsv', file('example.csv'));
    $csv_complete_filtered = array_filter(array_map('array_filter', $csv_complete_contents));
    $csv_num_rows = count($csv_complete_filtered);

    echo $csv_num_rows;

?>

Advertisement

Answer

I’ve done 2 versions of the code, the first one is based on what you already have, the second (IMHO) is a lot simpler.

Based on what you already have, the difference is that you currently filter on an entire row, so it will only count empty rows. This uses array_column() to extract the 4th column and then filters that. This also gives the number of filled rows, so I subtract it from the total rows…

$csv_complete_contents = array_map('str_getcsv', file('a.csv'));
$csv_complete_filtered = array_filter(array_column($csv_complete_contents, 3));
$csv_filled_rows = count($csv_complete_filtered);

echo count($csv_complete_contents) - $csv_filled_rows;

This uses a straight read CSV with fopen() and fgetcsv(). At each row it counts if the column is empty, this reduces the use of several array_ functions and makes it so much easier to read…

$fh = fopen("a.csv", "r");
$empty = 0;
$data = [];
while ( $row = fgetcsv($fh) )   {
    $data[] = $row;
    if ( empty($row [3]) )  {
        $empty++;
    }
}

echo $empty;
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement