0

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);
    }
}

2 Answers 2

3
$csv = array_map('str_getcsv', file('./temp.csv'));

foreach ($csv as $line) {
    if ($line[0] == 'Microsoft') {
        echo implode(', ',$line);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.