Breeke L
Breeke L

Reputation: 3

Get last occurrence of matched csv column when using fgetcsv

while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    if ($data[0] == "var") {
    }
}

I'm currently using fgetcsv to read a csv file ($handle) and return the row where the first column matches var. So far this is working well as $data[0] are unique values.

But going forward, there may be duplicate values in $data[0], how can I only return the last occurrence if there are duplicates?

Upvotes: 0

Views: 142

Answers (2)

AbraCadaver
AbraCadaver

Reputation: 79024

This will get the first occurrence if there are multiples, as it will break out of the loop after the first is found:

while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    if ($data[0] == "var") {
        $result = $data;
        break; // break out of the loop after the first is found
    }
}
print_r($result): // first one

This will get the last occurrence, as it will not break out of the loop and the last occurrence will be the last one assigned to the result:

while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    if ($data[0] == "var") {
        $result = $data;
        // loop keeps going until end of file
    }
}
print_r($result): // last one

You don't actually need to assign to $result as $data will contain the proper row after the break or after the end of the loop.

Upvotes: 1

Karol Samborski
Karol Samborski

Reputation: 2965

Just save row somewhere:

$lastRow = null;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    if ($data[0] == "var") {
        $lastRow = $data;
    }
}

Every occurrence of wanted row will override the lastRow variable so when the loop finish you will have there last row matching your criteria.

Upvotes: 0

Related Questions