File existence and info checks in PHP - Time & Space Complexity
When checking if files exist or getting their info, the time it takes depends on how many files we check.
We want to know how the time grows as we check more files.
Analyze the time complexity of the following code snippet.
$files = ['file1.txt', 'file2.txt', 'file3.txt'];
foreach ($files as $file) {
if (file_exists($file)) {
$size = filesize($file);
$modified = filemtime($file);
echo "$file: Size $size bytes, Modified $modified\n";
} else {
echo "$file does not exist.\n";
}
}
This code checks each file in a list to see if it exists, then gets its size and last modified time.
- Primary operation: Looping through each file and calling file_exists, filesize, and filemtime.
- How many times: Once for each file in the list.
Each file check takes some time, so more files mean more total time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 file checks and info calls |
| 100 | About 100 file checks and info calls |
| 1000 | About 1000 file checks and info calls |
Pattern observation: The total work grows directly with the number of files.
Time Complexity: O(n)
This means the time grows in a straight line as you check more files.
[X] Wrong: "Checking multiple files is just as fast as checking one file."
[OK] Correct: Each file check takes time, so more files add up and take longer overall.
Understanding how file checks scale helps you write efficient code when working with many files, a common real-world task.
"What if we used a function that checks all files at once? How would the time complexity change?"