Writing files (fwrite, file_put_contents) in PHP - Time & Space Complexity
When writing data to files in PHP, it's important to know how the time it takes grows as the data size grows.
We want to understand how the program's work changes when we write more or less data.
Analyze the time complexity of the following code snippet.
$data = str_repeat("A", 1000);
$file = fopen("example.txt", "w");
fwrite($file, $data);
fclose($file);
// Or using file_put_contents
file_put_contents("example2.txt", $data);
This code writes a string of data to a file using two common PHP functions.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Writing each byte of the string to the file.
- How many times: Once for each character in the data string.
As the size of the data string grows, the number of write operations grows roughly the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 write steps |
| 100 | About 100 write steps |
| 1000 | About 1000 write steps |
Pattern observation: The work grows directly with the amount of data to write.
Time Complexity: O(n)
This means the time to write grows in a straight line with the size of the data.
[X] Wrong: "Writing to a file is always instant, no matter how big the data is."
[OK] Correct: Writing takes longer when there is more data because each byte must be saved, so time grows with data size.
Understanding how file writing time grows helps you explain performance in real projects and shows you think about efficiency clearly.
"What if we buffered the data and wrote it in chunks instead of all at once? How would the time complexity change?"
Practice
Solution
Step 1: Understand the purpose of
This function writes data to a file in one step, handling opening and closing automatically.file_put_contentsStep 2: Compare with
fwritefwriterequires manual file opening and closing, so it's not as quick for simple writes.Final Answer:
file_put_contents -> Option DQuick Check:
Quick file write = file_put_contents [OK]
- Confusing fwrite as a standalone write function
- Thinking fopen writes data
- Assuming fclose writes data
fwrite?Solution
Step 1: Check the correct usage of
fwritefwriterequires a file handle fromfopenopened in write mode.Step 2: Validate the full sequence
$file = fopen('greet.txt', 'w'); fwrite($file, 'Hello'); fclose($file); opens the file in write mode, writes "Hello", then closes the file properly.Final Answer:
$file = fopen('greet.txt', 'w'); fwrite($file, 'Hello'); fclose($file); -> Option BQuick Check:
fopen + fwrite + fclose = correct syntax [OK]
- Calling fwrite without fopen file handle
- Missing file mode in fopen
- Not closing the file after writing
$filename = 'data.txt'; file_put_contents($filename, "Line1\n"); $file = fopen($filename, 'a'); fwrite($file, "Line2\n"); fclose($file); echo file_get_contents($filename);
Solution
Step 1: Analyze
This writes "Line1\n" to 'data.txt', creating or overwriting the file.file_put_contentscallStep 2: Analyze
Opening in append mode adds "Line2\n" after existing content.fopenwith 'a' mode andfwriteStep 3: Read file content with
It returns both lines concatenated with newlines.file_get_contentsFinal Answer:
Line1 Line2 -> Option CQuick Check:
Append mode adds lines, so both lines appear [OK]
- Assuming file_put_contents appends instead of overwrites
- Forgetting 'a' mode appends
- Expecting only last line output
$file = fopen('file.txt', 'r');
fwrite($file, 'Test');
fclose($file);Solution
Step 1: Check fopen mode
The file is opened in 'r' (read) mode, which does not allow writing.Step 2: Understand fwrite requirements
Writing requires 'w', 'a', or 'r+' mode; 'r' mode causes error on fwrite.Final Answer:
File opened in read mode, cannot write -> Option AQuick Check:
Write needs write mode, not 'r' [OK]
- Using 'r' mode when writing
- Ignoring file mode errors
- Assuming fwrite works on read-only handle
fwrite?Solution
Step 1: Check file open mode
$file = fopen('input.txt', 'w'); foreach ($lines as $line) { if (trim($line) !== '') { fwrite($file, $line . "\n"); } } fclose($file); opens file in 'w' mode, allowing writing and overwriting.Step 2: Validate input filtering
It usestrim($line) !== ''to skip empty or whitespace-only lines before writing.Step 3: Confirm writing and closing
Writes each valid line with newline and closes file properly.Final Answer:
Option A code snippet -> Option AQuick Check:
Trim check + fwrite + 'w' mode = correct [OK]
- Not trimming lines before writing
- Opening file in 'r' mode when writing
- Using file_put_contents without filtering
Ready to prove it?
Pass the test and this pattern moves unknown
