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 A
Quick Check:
Write needs write mode, not 'r' [OK]
Hint: Open file with 'w' or 'a' to write, not 'r' [OK]
Common Mistakes:
Using 'r' mode when writing
Ignoring file mode errors
Assuming fwrite works on read-only handle
5. You want to save user input lines into a file, but only if the input is not empty or whitespace. Which PHP code snippet correctly writes non-empty trimmed lines to "input.txt" using fwrite?
hard
A. $file = fopen('input.txt', 'w'); foreach ($lines as $line) { if (trim($line) !== '') { fwrite($file, $line . "\n"); } } fclose($file);
B. $file = fopen('input.txt', 'w'); foreach ($lines as $line) { fwrite($file, $line . "\n"); } fclose($file);
C. file_put_contents('input.txt', implode("\n", $lines));
D. $file = fopen('input.txt', 'r'); foreach ($lines as $line) { if ($line) { fwrite($file, $line); } } fclose($file);
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 uses trim($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 A
Quick Check:
Trim check + fwrite + 'w' mode = correct [OK]
Hint: Trim input lines and write only non-empty with fwrite [OK]
Common Mistakes:
Not trimming lines before writing
Opening file in 'r' mode when writing
Using file_put_contents without filtering
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.