PHP How to Convert CSV to Array Easily
fgetcsv() function inside a loop to read each line of the CSV file and store it as an array, like this: open the file with fopen(), then loop with while (($data = fgetcsv($handle)) !== false) to build your array.Examples
How to Think About It
Algorithm
Code
<?php $csvFile = 'data.csv'; $result = []; if (($handle = fopen($csvFile, 'r')) !== false) { while (($data = fgetcsv($handle)) !== false) { $result[] = $data; } fclose($handle); } print_r($result); ?>
Dry Run
Let's trace reading a CSV file with lines 'name,age' and 'Alice,30' through the code.
Open file
Open 'data.csv' for reading.
Read first line
Read 'name,age' and convert to ['name', 'age'].
Read second line
Read 'Alice,30' and convert to ['Alice', '30'].
| Iteration | Line Content | Array Result |
|---|---|---|
| 1 | name,age | ["name", "age"] |
| 2 | Alice,30 | ["Alice", "30"] |
Why This Works
Step 1: Open CSV file
Use fopen() to open the CSV file in read mode so PHP can access its contents.
Step 2: Read each line as CSV
Use fgetcsv() to read each line and automatically split it by commas into an array.
Step 3: Store lines in array
Add each array from fgetcsv() into a bigger array to hold all rows.
Step 4: Close file
Close the file with fclose() to free system resources.
Alternative Approaches
<?php $lines = file('data.csv'); $result = array_map('str_getcsv', $lines); print_r($result); ?>
<?php $file = new SplFileObject('data.csv'); $file->setFlags(SplFileObject::READ_CSV); $result = []; foreach ($file as $row) { if ($row !== [null]) { $result[] = $row; } } print_r($result); ?>
Complexity: O(n) time, O(n) space
Time Complexity
Reading each line once makes the time complexity linear, O(n), where n is the number of lines.
Space Complexity
Storing all lines in an array requires O(n) space proportional to the file size.
Which Approach is Fastest?
Using fgetcsv() with a loop is memory efficient and fast for large files; reading all lines at once with file() is simpler but uses more memory.
| Approach | Time | Space | Best For |
|---|---|---|---|
| fgetcsv() loop | O(n) | O(n) | Large files, memory efficient |
| file() + str_getcsv() | O(n) | O(n) | Small files, simpler code |
| SplFileObject READ_CSV | O(n) | O(n) | Large files, OOP style |
fclose() after reading can cause resource leaks.