CSV Diff — PHP source
Diff two CSVs by a key column: rows added, removed and changed, with the differing columns named. Quoted cells with commas, quotes and newlines are handled. Runs locally with a shareable link.
This is the PHP implementation — the same logic the interactive tool runs, in a shareable, citable form.
<?php
// csv-diff — key-based row diff of two RFC-4180 CSVs. PHP port (canonical TS:
// src/lib/csv-diff.ts; Go twin: cli/csv-diff). Mirrors the JS/Python ports:
// RFC-4180 parse (quoted cells with embedded commas, quotes, newlines; CR
// dropped; no-newline flush) with blank single-cell rows dropped as trailing
// noise, strict per-side validation (empty CSV, duplicate columns, ragged
// rows, duplicate keys — reported as error strings, never exceptions), then a
// key-based diff over the sorted key union: added/removed rows and changed
// rows whose differing column names come out sorted.
// RFC 4180 parser mirroring the TS loop: lenient quotes, CR dropped, a
// trailing field without a newline still completes its row.
function csv_to_rows(string $csv): array
{
$rows = [];
$field = '';
$row = [];
$inQ = false;
$n = strlen($csv);
for ($i = 0; $i < $n; $i++) {
$ch = $csv[$i];
if ($inQ) {
if ($ch === '"') {
if ($i + 1 < $n && $csv[$i + 1] === '"') { $field .= '"'; $i++; }
else { $inQ = false; }
} else {
$field .= $ch;
}
} elseif ($ch === '"') {
$inQ = true;
} elseif ($ch === ',') {
$row[] = $field; $field = '';
} elseif ($ch === "\n") {
$row[] = $field; $rows[] = $row; $row = []; $field = '';
} elseif ($ch !== "\r") {
$field .= $ch;
}
}
if ($field !== '' || $row !== []) { $row[] = $field; $rows[] = $row; }
return $rows;
}
// Blank single-cell rows are trailing noise to a diff, not data.
function csv_diff_parse(string $text): array
{
return array_values(array_filter(
csv_to_rows($text),
fn(array $r): bool => !(count($r) === 1 && $r[0] === '')
));
}
/**
* Strict per-side validation → [header, records]; RuntimeException carries
* the pinned strings (empty CSV, duplicate column, ragged row).
*/
function csv_diff_records(array $rows, string $label): array
{
if ($rows === []) throw new RuntimeException("$label: empty CSV");
$header = $rows[0];
$seen = [];
foreach ($header as $name) {
if (in_array($name, $seen, true)) throw new RuntimeException("$label: duplicate column \"$name\"");
$seen[] = $name;
}
$records = [];
for ($r = 1; $r < count($rows); $r++) {
if (count($rows[$r]) !== count($header))
throw new RuntimeException("$label: row " . ($r + 1) . ' has ' . count($rows[$r]) . ' cells, expected ' . count($header));
$records[] = array_combine($header, $rows[$r]);
}
return [$header, $records];
}
// Diff two CSVs by key column (default: the first header column).
function csv_diff(string $leftRaw, string $rightRaw, ?string $keyColumn = null): array
{
if (trim($leftRaw) === '' || trim($rightRaw) === '')
return ['rows' => [], 'same' => false, 'error' => 'Both inputs are required'];
try {
[$lheader, $lrecs] = csv_diff_records(csv_diff_parse($leftRaw), 'Left');
[$rheader, $rrecs] = csv_diff_records(csv_diff_parse($rightRaw), 'Right');
$key = $keyColumn ?? $lheader[0];
if (!in_array($key, $lheader, true)) return ['rows' => [], 'same' => false, 'error' => "Left: no key column \"$key\""];
if (!in_array($key, $rheader, true)) return ['rows' => [], 'same' => false, 'error' => "Right: no key column \"$key\""];
if ($lheader !== $rheader)
return ['rows' => [], 'same' => false, 'error' => 'Headers differ: left [' . implode(', ', $lheader) . '] vs right [' . implode(', ', $rheader) . ']'];
$index = function (array $records, string $label) use ($key): array {
$by = [];
foreach ($records as $rec) {
if (array_key_exists($rec[$key], $by)) throw new RuntimeException("$label: duplicate key \"{$rec[$key]}\"");
$by[$rec[$key]] = $rec;
}
return $by;
};
$leftBy = $index($lrecs, 'Left');
$rightBy = $index($rrecs, 'Right');
// Sorted, deduplicated union of both key sets.
$keys = array_keys($leftBy);
foreach (array_keys($rightBy) as $k) if (!array_key_exists($k, $leftBy)) $keys[] = $k;
sort($keys, SORT_STRING);
$out = [];
foreach ($keys as $k) {
$l = $leftBy[$k] ?? null;
$r = $rightBy[$k] ?? null;
if ($l === null) $out[] = ['key' => $k, 'type' => 'added', 'after' => $r];
elseif ($r === null) $out[] = ['key' => $k, 'type' => 'removed', 'before' => $l];
else {
$columns = [];
foreach ($lheader as $n) if ($n !== $key && $l[$n] !== $r[$n]) $columns[] = $n;
sort($columns, SORT_STRING);
if ($columns !== []) $out[] = ['key' => $k, 'type' => 'changed', 'columns' => $columns, 'before' => $l, 'after' => $r];
}
}
return ['rows' => $out, 'same' => $out === [], 'error' => null];
} catch (RuntimeException $e) {
return ['rows' => [], 'same' => false, 'error' => $e->getMessage()];
}
}
// Example:
// csv_diff("id,name\n1,Ada\n2,Bob", "id,name\n1,Ada\n2,Robert\n3,New")["rows"]
// → [["key" => "2", "type" => "changed", "columns" => ["name"], …],
// ["key" => "3", "type" => "added", "after" => ["id" => "3", "name" => "New"]]]
Also available in 12 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →