The file is opened with 'r' (read) mode, which does not allow writing.
Step 2: Understand fputcsv requirements
fputcsv() requires the file to be opened in write ('w') or append ('a') mode to write data.
Final Answer:
File opened in read mode instead of write mode -> Option D
Quick Check:
Open file in write mode before writing [OK]
Hint: Open file with 'w' or 'a' before writing CSV [OK]
Common Mistakes:
Opening file in 'r' mode when writing
Forgetting to close the file
Misunderstanding fputcsv() input
5. You want to read a CSV file and write only rows where the third column is greater than 50 to a new CSV file. Which code snippet correctly implements this?
hard
A. $in = fopen('input.csv', 'w');
$out = fopen('output.csv', 'r');
while (($row = fgetcsv($in)) !== false) {
if ($row[2] > 50) {
fputcsv($out, $row);
}
}
fclose($in);
fclose($out);
B. $in = fopen('input.csv', 'r');
$out = fopen('output.csv', 'w');
while (($row = fgetcsv($in)) !== false) {
if ($row[2] > 50) {
fputcsv($out, $row);
}
}
fclose($in);
fclose($out);
C. $in = fopen('input.csv', 'r');
$out = fopen('output.csv', 'w');
while (($row = fgetcsv($out)) !== false) {
if ($row[2] > 50) {
fputcsv($in, $row);
}
}
fclose($in);
fclose($out);
D. $in = fopen('input.csv', 'r');
$out = fopen('output.csv', 'w');
while (($row = fgets($in)) !== false) {
if ($row[2] > 50) {
fputcsv($out, $row);
}
}
fclose($in);
fclose($out);
Solution
Step 1: Open input file for reading and output file for writing
Use 'r' mode for reading input and 'w' mode for writing output.
Step 2: Read each CSV row with fgetcsv() from input and check third column
Use fgetcsv($in) to read rows, then check if $row[2] > 50.
Step 3: Write qualifying rows to output with fputcsv()
If condition passes, write row to output file using fputcsv($out, $row).
Final Answer:
Code snippet B correctly reads, filters, and writes CSV rows -> Option B
Quick Check:
Read with fgetcsv(), filter by column, write with fputcsv() [OK]
Hint: Read with fgetcsv(), filter rows, write with fputcsv() [OK]
Common Mistakes:
Opening files with wrong modes
Using fgets() instead of fgetcsv() for CSV reading
Mixing input and output file handles
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.