Bird
0
0

You want to read a file line by line and store only lines longer than 10 characters into an array. Which code snippet correctly does this?

hard📝 Application Q8 of 15
PHP - File Handling
You want to read a file line by line and store only lines longer than 10 characters into an array. Which code snippet correctly does this?
A$fp = fopen('file.txt', 'r'); $lines = []; while ($line = fgets($fp)) { if (strlen($line) > 10) { $lines[] = $line; } } fclose($fp);
B$lines = file('file.txt'); foreach ($lines as $line) { if (strlen($line) > 10) { $lines[] = $line; } }
C$fp = fopen('file.txt', 'r'); $lines = []; while (!feof($fp)) { $line = fread($fp, 10); $lines[] = $line; } fclose($fp);
D$lines = file_get_contents('file.txt'); $lines = explode("\n", $lines); foreach ($lines as $line) { if (strlen($line) > 10) { $lines[] = $line; } }
Step-by-Step Solution
Solution:
  1. Step 1: Analyze each option's logic

    $fp = fopen('file.txt', 'r'); $lines = []; while ($line = fgets($fp)) { if (strlen($line) > 10) { $lines[] = $line; } } fclose($fp); reads line by line with fgets(), checks length, and stores lines longer than 10 chars correctly. $lines = file('file.txt'); foreach ($lines as $line) { if (strlen($line) > 10) { $lines[] = $line; } } modifies the same array while iterating causing issues. $fp = fopen('file.txt', 'r'); $lines = []; while (!feof($fp)) { $line = fread($fp, 10); $lines[] = $line; } fclose($fp); reads fixed bytes, not lines. $lines = file_get_contents('file.txt'); $lines = explode("\n", $lines); foreach ($lines as $line) { if (strlen($line) > 10) { $lines[] = $line; } } appends to same array while iterating causing infinite loop.
  2. Step 2: Confirm correct approach

    $fp = fopen('file.txt', 'r'); $lines = []; while ($line = fgets($fp)) { if (strlen($line) > 10) { $lines[] = $line; } } fclose($fp); uses proper file reading and filtering logic without modifying array during iteration.
  3. Final Answer:

    Option A code snippet -> Option A
  4. Quick Check:

    Read line by line + filter length = $fp = fopen('file.txt', 'r'); $lines = []; while ($line = fgets($fp)) { if (strlen($line) > 10) { $lines[] = $line; } } fclose($fp); [OK]
Quick Trick: Use fgets() loop and strlen() to filter lines [OK]
Common Mistakes:
  • Modifying array while iterating it
  • Using fread() to read lines incorrectly
  • Using file_get_contents() without splitting lines

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes