Home » Php » PHP iterate through each row of csv and return row with matching element

PHP iterate through each row of csv and return row with matching element

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have a csv file called data.csv.

Here’s a sample of what’s in data.csv

Microsoft,2020-02-13,"Sample",tt,aa,qq,w,ee,rr,tt,", ",", ",", ","2020-02-13 16:03:08"
Google,2020-02-13,"HQ",tt,aa,qq,w,ee,rr,tt,", ",", ",", ","2020-02-13 16:10:48"

I’m trying to iterate through each row of the csv and check if user inputted variable (lets say var=”Microsoft”) matches the first value in any row. If it does match, then return all the elements in that row as an array. (tried this using fgetcsv but returns whole csv file)

Here’s what I have tried so far:

foreach ($csv as $line) {
    if ($line[0] == 'Microsoft') {
        $file = fopen("data.csv","r");
        echo(fgetcsv($file));
        fclose($file);
    }
}
How to&Answers:
$csv = array_map('str_getcsv', file('./temp.csv'));

foreach ($csv as $line) {
    if ($line[0] == 'Microsoft') {
        echo implode(', ',$line);
    }
}

Answer:

If the first column’s value is suitable as an array index. You can use array_column to re-index by your first column:

<?php
$result = array_column(array_map('str_getcsv', file('data.csv')), null, 0)['Microsoft'] ?? null;