CSV file reading and writing in PHP - Time & Space Complexity
When working with CSV files in PHP, it's important to know how the time to read or write grows as the file gets bigger.
We want to understand how the program's speed changes when the number of rows in the CSV changes.
Analyze the time complexity of the following code snippet.
$inputFile = fopen('data.csv', 'r');
$outputFile = fopen('output.csv', 'w');
while (($row = fgetcsv($inputFile)) !== false) {
// Process row data
fputcsv($outputFile, $row);
}
fclose($inputFile);
fclose($outputFile);
This code reads each row from a CSV file and writes it to another CSV file, processing one row at a time.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Reading each row from the CSV file and writing it to another file.
- How many times: Once for every row in the CSV file (let's call the number of rows n).
As the number of rows grows, the program reads and writes more rows one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 reads and 10 writes |
| 100 | About 100 reads and 100 writes |
| 1000 | About 1000 reads and 1000 writes |
Pattern observation: The number of operations grows directly with the number of rows. Double the rows, double the work.
Time Complexity: O(n)
This means the time to read and write grows in a straight line with the number of rows in the CSV file.
[X] Wrong: "Reading a CSV file is always very fast and does not depend on file size."
[OK] Correct: The program reads each row one by one, so bigger files take more time because there are more rows to handle.
Understanding how file reading and writing scales helps you explain your code's efficiency clearly and shows you know how programs behave with bigger data.
"What if we read the entire CSV file into an array first, then process it? How would the time complexity change?"
Practice
Solution
Step 1: Understand CSV reading functions
PHP providesfgetcsv()to read a line from a CSV file and convert it into an array of values.Step 2: Differentiate from writing functions
fputcsv()writes arrays to CSV files, whilefread()andfwrite()handle raw file reading/writing without CSV parsing.Final Answer:
fgetcsv() -> Option AQuick Check:
Read CSV line as array = fgetcsv() [OK]
- Confusing fgetcsv() with fputcsv()
- Using fread() which reads raw data, not CSV parsed
- Trying to read CSV without parsing into arrays
Solution
Step 1: Understand fopen modes
Mode 'w' opens a file for writing and truncates it if it exists, perfect for writing CSV files.Step 2: Check other modes
'r' is read-only, 'rw' is invalid, 'x' creates a new file but fails if it exists.Final Answer:
$file = fopen('data.csv', 'w'); -> Option CQuick Check:
Open file for writing = 'w' mode [OK]
- Using 'r' mode when intending to write
- Using invalid mode 'rw'
- Using 'x' which fails if file exists
$file = fopen('data.csv', 'r');
$data = fgetcsv($file);
fclose($file);
print_r($data);Assuming the first line of
data.csv is:John,Doe,30Solution
Step 1: Understand fgetcsv() output
fgetcsv() reads one CSV line and returns an array splitting values by commas.Step 2: Analyze given CSV line
The line 'John,Doe,30' splits into array elements: 'John', 'Doe', and '30'.Final Answer:
Array ( [0] => John [1] => Doe [2] => 30 ) -> Option AQuick Check:
fgetcsv() splits CSV line into array [OK]
- Expecting a string instead of an array
- Assuming fgetcsv returns raw line string
- Not closing the file after reading
$file = fopen('output.csv', 'r');
fputcsv($file, ['Alice', 'Smith', 25]);
fclose($file);Solution
Step 1: Check fopen mode
The file is opened with 'r' (read) mode, which does not allow writing.Step 2: Understand fputcsv requirements
fputcsv() requires the file to be opened in write ('w') or append ('a') mode to write data.Final Answer:
File opened in read mode instead of write mode -> Option DQuick Check:
Open file in write mode before writing [OK]
- Opening file in 'r' mode when writing
- Forgetting to close the file
- Misunderstanding fputcsv() input
Solution
Step 1: Open input file for reading and output file for writing
Use 'r' mode for reading input and 'w' mode for writing output.Step 2: Read each CSV row with fgetcsv() from input and check third column
Usefgetcsv($in)to read rows, then check if$row[2] > 50.Step 3: Write qualifying rows to output with fputcsv()
If condition passes, write row to output file usingfputcsv($out, $row).Final Answer:
Code snippet B correctly reads, filters, and writes CSV rows -> Option BQuick Check:
Read with fgetcsv(), filter by column, write with fputcsv() [OK]
- Opening files with wrong modes
- Using fgets() instead of fgetcsv() for CSV reading
- Mixing input and output file handles
Ready to prove it?
Pass the test and this pattern moves unknown
