Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to open a CSV file for reading.
PHP
<?php $handle = fopen('data.csv', '[1]'); ?>
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'w' or 'a' mode which are for writing or appending.
Forgetting to put the mode in quotes.
✗ Incorrect
To read a CSV file, you open it in read mode using 'r'.
2fill in blank
mediumComplete the code to read a line from the CSV file as an array.
PHP
<?php $handle = fopen('data.csv', 'r'); $row = fgetcsv([1]); ?>
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable that was not assigned to fopen.
Passing a string filename instead of the file handle.
✗ Incorrect
The variable holding the file pointer is $handle, which is passed to fgetcsv to read a line.
3fill in blank
hardFix the error in the code to write an array as a CSV line.
PHP
<?php $handle = fopen('output.csv', 'w'); fputcsv([1], ['apple', 'banana', 'cherry']); fclose($handle); ?>
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Passing an undefined variable to fputcsv.
Confusing the file handle variable name.
✗ Incorrect
fputcsv requires the file handle as the first argument, which is $handle here.
4fill in blank
hardFill both blanks to read all lines from a CSV file into an array.
PHP
<?php $handle = fopen('data.csv', 'r'); $data = []; while (($row = fgetcsv([1])) [2] false) { $data[] = $row; } fclose($handle); ?>
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '==' instead of '!==' in the while condition.
Using wrong variable for the file handle.
✗ Incorrect
We use $handle as the file pointer and check that fgetcsv does not return false to continue reading lines.
5fill in blank
hardFill all three blanks to write multiple rows to a CSV file using a loop.
PHP
<?php
$rows = [
['John', 'Doe', 30],
['Jane', 'Smith', 25],
['Bob', 'Johnson', 40]
];
$handle = fopen('people.csv', 'w');
foreach ([1] as [2]) {
fputcsv([3], $row);
}
fclose($handle);
?> Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong variable names in the foreach loop.
Passing wrong variable to fputcsv.
✗ Incorrect
The foreach loops over $rows as $row, and fputcsv writes each $row to the file handle $handle.