Bird
0
0

What will be the output of this PHP code?

medium📝 Predict Output Q13 of 15
PHP - File Handling
What will be the output of this PHP code?
$filename = 'data.txt';
file_put_contents($filename, "Line1\n");
$file = fopen($filename, 'a');
fwrite($file, "Line2\n");
fclose($file);
echo file_get_contents($filename);
ALine2
BLine1
CLine1 Line2
DError: file not found
Step-by-Step Solution
Solution:
  1. Step 1: Analyze file_put_contents call

    This writes "Line1\n" to 'data.txt', creating or overwriting the file.
  2. Step 2: Analyze fopen with 'a' mode and fwrite

    Opening in append mode adds "Line2\n" after existing content.
  3. Step 3: Read file content with file_get_contents

    It returns both lines concatenated with newlines.
  4. Final Answer:

    Line1 Line2 -> Option C
  5. Quick Check:

    Append mode adds lines, so both lines appear [OK]
Quick Trick: file_put_contents overwrites; fopen 'a' appends [OK]
Common Mistakes:
  • Assuming file_put_contents appends instead of overwrites
  • Forgetting 'a' mode appends
  • Expecting only last line output

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes