0
0
PhpHow-ToBeginner · 2 min read

PHP How to Convert CSV to Array Easily

Use PHP's 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

InputCSV file content: name,age Alice,30 Bob,25
Output[["name", "age"], ["Alice", "30"], ["Bob", "25"]]
InputCSV file content: product,price,quantity Pen,1.5,10 Notebook,2.0,5
Output[["product", "price", "quantity"], ["Pen", "1.5", "10"], ["Notebook", "2.0", "5"]]
InputEmpty CSV file
Output[]
🧠

How to Think About It

To convert a CSV file to an array in PHP, open the file and read it line by line. Each line is split by commas into an array of values. Collect these arrays into a bigger array representing all rows.
📐

Algorithm

1
Open the CSV file for reading.
2
Create an empty array to hold all rows.
3
Loop through each line of the file using a CSV parser.
4
For each line, convert it into an array of values.
5
Add this array to the main array.
6
Close the file and return the array.
💻

Code

php
<?php
$csvFile = 'data.csv';
$result = [];
if (($handle = fopen($csvFile, 'r')) !== false) {
    while (($data = fgetcsv($handle)) !== false) {
        $result[] = $data;
    }
    fclose($handle);
}
print_r($result);
?>
Output
Array ( [0] => Array ( [0] => name [1] => age ) [1] => Array ( [0] => Alice [1] => 30 ) [2] => Array ( [0] => Bob [1] => 25 ) )
🔍

Dry Run

Let's trace reading a CSV file with lines 'name,age' and 'Alice,30' through the code.

1

Open file

Open 'data.csv' for reading.

2

Read first line

Read 'name,age' and convert to ['name', 'age'].

3

Read second line

Read 'Alice,30' and convert to ['Alice', '30'].

IterationLine ContentArray Result
1name,age["name", "age"]
2Alice,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

file() and str_getcsv()
php
<?php
$lines = file('data.csv');
$result = array_map('str_getcsv', $lines);
print_r($result);
?>
Reads whole file into memory first, simpler code but uses more memory for large files.
SplFileObject with READ_CSV flag
php
<?php
$file = new SplFileObject('data.csv');
$file->setFlags(SplFileObject::READ_CSV);
$result = [];
foreach ($file as $row) {
    if ($row !== [null]) {
        $result[] = $row;
    }
}
print_r($result);
?>
Uses object-oriented approach, good for large files and more control.

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.

ApproachTimeSpaceBest For
fgetcsv() loopO(n)O(n)Large files, memory efficient
file() + str_getcsv()O(n)O(n)Small files, simpler code
SplFileObject READ_CSVO(n)O(n)Large files, OOP style
💡
Always check if the file opened successfully before reading to avoid errors.
⚠️
Forgetting to close the file with fclose() after reading can cause resource leaks.