Using PHP to search CSV by Column?

Issue

Having trouble searching CSV file by Column. For example, I have the following CSV file:

NAME, HAS AN IPHONE, HAS ANDROID

bob, yes, no,

fred, no, yes,

How could I search column 2 for a ‘yes’ value using php,
then return only the rows with "yes" in second column results?

Solution

Assuming you have already parsed the csv file into an array.
The second parameter of array_keys function is mixed $search_value

If specified, then only keys containing these values are returned.

To search a specific column, use array_column:

$res = array_keys(array_column($csv, 1), "yes");

See test at eval.in; This would return keys of of all “yes” matches in the second column.

Answered By – Jonny 5

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published