How can a 2-dimensional array be utilized to efficiently manage and update CSV data in PHP?

To efficiently manage and update CSV data in PHP using a 2-dimensional array, you can read the CSV file into the array, perform any necessary operations on the data, and then write the updated array back to the CSV file. This approach allows for easy manipulation of the data within the array before saving it back to the CSV file.

// Read CSV data into a 2-dimensional array
$csvData = [];
if (($handle = fopen("data.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $csvData[] = $data;
    }
    fclose($handle);
}

// Perform operations on the data
foreach ($csvData as $row) {
    // Update data as needed
}

// Write updated data back to the CSV file
if (($handle = fopen("data.csv", "w")) !== FALSE) {
    foreach ($csvData as $row) {
        fputcsv($handle, $row);
    }
    fclose($handle);
}