Code Logo

CSV Parser

Published at24 Jul 2026
PHP String Handling Hard 0 views
Like0

Write a PHP function that parses a CSV (comma-separated values) string into an array of rows, where each row is itself an array of field values.

Split the CSV text into individual lines using explode() with the newline character as delimiter. For each non-empty line, call str_getcsv() which correctly parses CSV fields handling quoted values, embedded commas, and escaped quotes.

The str_getcsv() function respects standard CSV formatting rules: fields enclosed in double quotes can contain commas, and a double quote character inside a quoted field is represented by two double quotes.

Edge cases include an empty string (return []), a single field (return one row with one field), quoted fields with commas inside, and escaped double quotes.

Time complexity is O(n). Space complexity is O(n) for the result array.

CSV parsing requires careful handling of the CSV specification, particularly quoted fields that may contain commas and newlines. PHP's str_getcsv() implements the RFC 4180 CSV standard, correctly handling edge cases that a naive explode() approach would miss.

The explode and str_getcsv combination handles most CSV formats correctly. For production use, fgetcsv() on a stream handle provides additional features like configurable delimiters and enclosure characters.

Example Input & Output

Example 1
Input
"a,b\n1,2\n3,4"
Output
[["a","b"],["1","2"],["3","4"]]
Example 2
Input
"1,\"hello, world\""
Output
[["1","hello, world"]]
Example 3
Input
""
Output
[]
Example 4
Input
"a"
Output
[["a"]]
Example 5
Input
"x,y,z"
Output
[["x","y","z"]]

Algorithm Flow

Recommendation Algorithm Flow for CSV Parser
Recommendation Algorithm Flow for CSV Parser

Solution Approach

Write a PHP function that parses a CSV (comma-separated values) string into an array of rows, where each row is itself an array of field values.

Split the CSV text into individual lines using explode() with the newline character as delimiter. For each non-empty line, call str_getcsv() which correctly parses CSV fields handling quoted values, embedded commas, and escaped quotes.

The str_getcsv() function respects standard CSV formatting rules: fields enclosed in double quotes can contain commas, and a double quote character inside a quoted field is represented by two double quotes.

Edge cases include an empty string (return []), a single field (return one row with one field), quoted fields with commas inside, and escaped double quotes.

Time complexity is O(n). Space complexity is O(n) for the result array.

Best Answers

php - Approach 1
<?php
function parseCsv($csv) {
    $r=[];foreach(explode("\n",$csv) as $l){if($l!==''){$r[]=str_getcsv($l);}}return $r;
}