How can PHP be used to limit the number of elements in a CSV file and remove the oldest entries in a FIFO fashion?

To limit the number of elements in a CSV file and remove the oldest entries in a FIFO fashion, you can read the CSV file into an array, check its length, and if it exceeds the desired limit, remove the oldest entries. Then, write the updated array back to the CSV file.

<?php
$filename = 'data.csv';
$maxElements = 100;

// Read CSV file into an array
$data = array_map('str_getcsv', file($filename));

// Check if the array exceeds the limit
if (count($data) > $maxElements) {
    $data = array_slice($data, count($data) - $maxElements);
}

// Write the updated array back to the CSV file
$fp = fopen($filename, 'w');
foreach ($data as $fields) {
    fputcsv($fp, $fields);
}
fclose($fp);
?>