Bird
0
0

How can you read a file into an array of trimmed lines (no trailing newlines) using PHP?

hard📝 Application Q9 of 15
PHP - File Handling
How can you read a file into an array of trimmed lines (no trailing newlines) using PHP?
A$lines = file('file.txt', FILE_IGNORE_NEW_LINES);
B$lines = trim(file_get_contents('file.txt'));
C$lines = array_map('trim', file('file.txt'));
D$lines = explode("\n", trim(file_get_contents('file.txt')));
Step-by-Step Solution
Solution:
  1. Step 1: Understand file() and trimming

    file() returns lines with newlines. Using array_map('trim', ...) removes whitespace including newlines from each line.
  2. Step 2: Compare options

    $lines = array_map('trim', file('file.txt')); correctly trims each line. $lines = trim(file_get_contents('file.txt')); trims whole string, not lines. $lines = file('file.txt', FILE_IGNORE_NEW_LINES); uses a flag that removes newlines but is not always available or reliable. $lines = explode("\n", trim(file_get_contents('file.txt'))); splits trimmed string but may miss last line if no newline.
  3. Final Answer:

    $lines = array_map('trim', file('file.txt')); -> Option C
  4. Quick Check:

    Trim each line with array_map('trim') [OK]
Quick Trick: Use array_map('trim', file()) to trim lines [OK]
Common Mistakes:
  • Trimming whole file string instead of lines
  • Using FILE_IGNORE_NEW_LINES flag incorrectly
  • Splitting string manually without trimming

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes