Hello Developers,
How to Delete And Update particular row of CSV file in php.
<a href=""></a>
Thanks & Regards,
Dinesh Thakur
CSV is not a database. You cannot reliably change a single row in-place. The safe pattern (as already hinted) is: read each row, decide whether to update or skip it, write the result to a temporary file, then replace the original. Use the CSV helpers so quoted commas and newlines are handled correctly.
<?php
function csv_update_or_delete($file, $keyColumn, $keyValue, array $updates = null) {
$in = fopen($file, 'r');
if (!$in || !flock($in, LOCK_EX)) return false;
$tmp = $file . '.tmp';
$out = fopen($tmp, 'w');
if (!$out) { flock($in, LOCK_UN); fclose($in); return false; }
// assume header row; use names if provided, else pass a numeric index for $keyColumn
$header = fgetcsv($in);
$map = array_flip($header);
$keyIndex = is_int($keyColumn) ? $keyColumn : $map[$keyColumn];
fputcsv($out, $header);
$changed = false;
while (($row = fgetcsv($in)) !== false) {
$isMatch = isset($row[$keyIndex]) && (string)$row[$keyIndex] === (string)$keyValue;
if ($isMatch && is_array($updates)) {
foreach ($updates as $col => $val) {
$i = is_int($col) ? $col : ($map[$col] ?? null);
if ($i !== null) $row[$i] = $val;
}
fputcsv($out, $row); // update
$changed = true;
} elseif ($isMatch && $updates === null) {
$changed = true; // delete (skip writing)
} else {
fputcsv($out, $row); // keep
}
}
fflush($out); fclose($out); flock($in, LOCK_UN); fclose($in);
if ($changed) return rename($tmp, $file);
unlink($tmp); return false;
}
// examples:
// update row with id=42
csv_update_or_delete('data.csv', 'id', '42', ['email' => 'new@example.com']);
// delete row with id=42
csv_update_or_delete('data.csv', 'id', '42'); Notes:
explode.But how will anyone know it was updated if you delete it first?
In case you meant delete or update, then
For update:
For deletion:
super secret shortcut for the above steps
In all seriousness though, seeing as your file isn't very big you could probably store every line in an array, manipulate/delete those and write each value back to a file, it's nothing fancy and plenty of information already exists. Especially since it's a very general question with hardly any specifics or prework.
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.