0
0
PHPprogramming~5 mins

File existence and info checks in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: File existence and info checks
O(n)
Understanding Time 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.

Scenario Under Consideration

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.

Identify Repeating Operations
  • Primary operation: Looping through each file and calling file_exists, filesize, and filemtime.
  • How many times: Once for each file in the list.
How Execution Grows With Input

Each file check takes some time, so more files mean more total time.

Input Size (n)Approx. Operations
10About 10 file checks and info calls
100About 100 file checks and info calls
1000About 1000 file checks and info calls

Pattern observation: The total work grows directly with the number of files.

Final Time Complexity

Time Complexity: O(n)

This means the time grows in a straight line as you check more files.

Common Mistake

[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.

Interview Connect

Understanding how file checks scale helps you write efficient code when working with many files, a common real-world task.

Self-Check

"What if we used a function that checks all files at once? How would the time complexity change?"