How to Use Associative Arrays in fputcsv PHP Code Examples

Last Updated on

CraftyTechie is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

Associative arrays with fputcsv PHP Code Example

This article includes examples of associative arrays with fputcsv in PHP. If you’re familiar with reading and writing CSV files in PHP, you can jump straight to the last two sections of the artice.

<?php
$employees = [
    ['Id', 'Name', 'Age', 'Salary', 'Department'],
    ['1', 'Anna', '30', 20000, 'Finance'],
    ['2', 'Adam', '25', 15000, 'IT'],
    ['3', 'Bob', '32', 25000, 'Finance'],
    ['4', 'Cara', '20', 12000, 'Logistics'],
    ['5', 'Daniel', '28', 27000, 'Engineering'],
];
 
//Creates a new file employee_records.csv
$file = fopen('employee_records.csv', 'w'); //w is the flag for write mode.
 
if($file === false)
{
    die('Cannot open the file');
}
 
foreach($employees as $employee)
{
    //Formats the employee record as CSV and writes it out employee_records.csv
    fputcsv($file, $employee);
}
 
//Closes the file.
fclose($file);
?>

CSV PHP Code Examples and Learning Path

Introduction

PHP fputcsv is a built-in function for formatting arrays into CSV and writing it out to a file pointer. The fputcsv in PHP makes lives easier by doing all the hard work behind the scenes and letting programmers focus on the data that is supposed to be pushed to a CSV file. This function takes a file pointer and a string array representing the data in the output CSV file.

fputcsv( resource $stream, array $fields, string $separator = ",", string $enclosure = "\"", string $escape = "\\", string $eol = "\n"): int|false

A comma-separated file or a CSV is a text-based file to store tabular data. CSV files have data fields separated by commas and thus the name comma-separated file. Here’s a glimpse of what a CSV file looks like when opened up in a text editor.

associative arrays with fputcsv

There’s an in-depth article about reading and writing CSV files in PHP. This article can take you from grounds up on handling CSV files in PHP. This article is concerned with associative arrays with fputcsv in PHP. We’ll see some examples of handling and writing an associative array out to a CSV.

#1 – Indexed Array with fputcsv in PHP

Before jumping into complexities, let’s see a straightforward indexed array first. An indexed array has numeric keys, and the values can be any type. Here’s an example of an indexed array.

$employees = [
    ['Id', 'Name', 'Age', 'Salary', 'Department'],
    ['1', 'Anna', '30', 20000, 'Finance'],
    ['2', 'Adam', '25', 15000, 'IT'],
    ['3', 'Bob', '32', 25000, 'Finance'],
    ['4', 'Cara', '20', 12000, 'Logistics'],
    ['5', 'Daniel', '28', 27000, 'Engineering'],
];

The keys are not explicitly typed when defining the array. However, if we print this array out to the console, PHP shows us the keys too. Here’s how.

Array
(
    [0] => Array
        (
            [0] => Id
            [1] => Name
            [2] => Age
            [3] => Salary
            [4] => Department
        )
 
    [1] => Array
        (
            [0] => 1
            [1] => Anna
            [2] => 30
            [3] => 20000
            [4] => Finance
        )
 
    [2] => Array
        (
            [0] => 2
            [1] => Adam
            [2] => 25
            [3] => 15000
            [4] => IT
        )
 
    [3] => Array
        (
            [0] => 3
            [1] => Bob
            [2] => 32
            [3] => 25000
            [4] => Finance
        )
 
    [4] => Array
        (
            [0] => 4
            [1] => Cara
            [2] => 20
            [3] => 12000
            [4] => Logistics
        )
 
    [5] => Array
        (
            [0] => 5
            [1] => Daniel
            [2] => 28
            [3] => 27000
            [4] => Engineering
        )
)

The index starts from zero, and you can see that the first index has an array defining headers for the rest of the data. 

Example

Let’s write this indexed array to a CSV file using PHP fputcsv.

<?php
$employees = [
    ['Id', 'Name', 'Age', 'Salary', 'Department'],
    ['1', 'Anna', '30', 20000, 'Finance'],
    ['2', 'Adam', '25', 15000, 'IT'],
    ['3', 'Bob', '32', 25000, 'Finance'],
    ['4', 'Cara', '20', 12000, 'Logistics'],
    ['5', 'Daniel', '28', 27000, 'Engineering'],
];
 
//Creates a new file employee_records.csv
$file = fopen('employee_records.csv', 'w'); //w is the flag for write mode.
 
if($file === false)
{
    die('Cannot open the file');
}
 
foreach($employees as $employee)
{
    //Formats the employee record as CSV and writes it out employee_records.csv
    fputcsv($file, $employee);
}
 
//Closes the file.
fclose($file);
?>

So, the example creates a new CSV file, ‘employee_records.csv’ using the fopen function in PHP.  Then, the foreach loops iterate over this array, and the PHP fputcsv writes every sub-array as a data record to the output CSV file. Here’s the output after running this example.

Id,Name,Age,Salary,Department
1,Anna,30,20000,Finance
2,Adam,25,15000,IT
3,Bob,32,25000,Finance
4,Cara,20,12000,Logistics
5,Daniel,28,27000,Engineering

The example is a review of an indexed array to CSV using the fputcsv. Now, let’s move on to the main subject of using associative arrays with fputcsv in PHP.

#2 – Associative Array with fputcsv in PHP – I

PHP Associate array has named keys. They are similar to dictionaries or hash maps. We’ll see how to use associative arrays with fputcsv. Here’s an associative array with similar data as seen above.

$employees = [
    ["Id" => '1', "Name" => 'Anna', "Age" => '30', "Salary" => 20000, "Department" => 'Finance'],
    ["Id" => '2', "Name" => 'Adam', "Age" => '25', "Salary" => 15000, "Department" => 'IT'],
    ["Id" => '3', "Name" => 'Bob', "Age" => '32', "Salary" => 25000, "Department" => 'Finance'],
    ["Id" => '4', "Name" => 'Cara', "Age" => '20', "Salary" => 12000, "Department" => 'Logistics'],
    ["Id" => '5', "Name" => 'Daniel', "Age" => '28', "Salary" => 27000, "Department" => 'Engineering'],
];

The sub-arrays are associative. In this instance, we do not have a separate header array. So, we need to get headers from one of the sub-arrays. PHP array_keys function can help us here. Let’s see the complete example.

<?php
//Creates a new file employee_records.csv
$file = fopen('employee_records.csv', 'w'); //w is the flag for write mode.
 
if($file === false)
{
    die('Cannot open the file');
}
 
$headers = array_keys($employees[0]);
 
//Write headers
fputcsv($file, $headers);
 
foreach($employees as $employee)
{
    //Formats the employee record as CSV and writes it out employee_records.csv
    fputcsv($file, $employee);
}
 
//Closes the file.
fclose($file);
?>

The example is similar to what we have seen before with a header variable. The header stores the output of the array_keys function, and the fputcsv call then write the header out to the CSV file. Moreover, the output remains the same as in the indexed array example.

#3 – Associative Array with fputcsv in PHP – II

Yet another variant of associative array that groups data on an attribute. Here’s the same data in the said form.

$employees = [
    "Id"   => ["1", "2", "3", "4", "5"],
    "Name" => ["Anna", "Adam", "Bob", "Cara", "Daniel"],
    "Age"  => ["30", "25", "32", "20", "28"],
    "Salary" => [20000, 15000, 25000, 12000, 27000],
    "Department" => ["Finance", "IT", "Finance", "Logistics", "Engineering"]
];

The data groups by attribute here. For instance, the attribute “Name” includes all the names. A column forms a relevant data record. So, the array is supposed to be sliced by column, and fortunately, there is a function in PHP for it, array_column. So, let’s see how that works.

<?php 
//Creates a new file employee_records.csv
$file = fopen('employee_records.csv', 'w'); //w is the flag for write mode.
 
if($file === false)
{
    die('Cannot open the file');
}
 
$headers = array_keys($employees);
 
//Write headers
fputcsv($file, $headers);
 
for($i = 0; $i < count($employees['Id']); $i++)
{
    //Formats the employee record as CSV and writes it out employee_records.csv
    fputcsv($file, array_column($employees, $i));
}
 
//Closes the file.
fclose($file);
?>

The example is similar to others up to the loop. The loop counts on the “Id” array because that is the most reliable attribute to rely upon. The fputcsv writes the return value of the array_column function, which slices the array column by column. The output remains the same here as well.

Reading CSV files in PHP

Here’s an example of reading the CSV file we have created in the examples above.

<?php
$employees = [];
 
//Creates a new file employee_records.csv
$file = fopen('employee_records.csv', 'r'); //w is the flag for write mode.
 
if($file === false)
{
    die('Cannot open the file');
}
 
//As long as there are records in the CSV file.
while(($row = fgetcsv($file)) !== false)
{
    //Push the data record to employees array.
    array_push($employees, $row);
}
 
//Closes the file.
fclose($file);
 
print_r($employees);
?>

The example reads the CSV file with the fgetcsv function pushes the CSV records to an array of employees.

Using Associative Arrays in fputcsv

Voila! That was a lot of ground to cover. This article starts with an example of an indexed array to CSV, followed by working two variants of associative arrays with fputcsv in PHP. The fputcsv in PHP is a crucial function for handling writing CSV files. Finally, an example of reading a CSV file with fgetcsv in PHP. 

That’s all about associative arrays with fputcsv. If you are curious about learning PHP, check out some intuitive and in-depth articles and tutorials at FuelingPHP.

Want to learn more about PHP?

We have many fun articles related to PHP. You can explore these to learn more about PHP.

Did you find this article helpful?

Join the best weekly newsletter where I deliver content on building better web applications. I curate the best tips, strategies, news & resources to help you develop highly-scalable and results-driven applications.

Build Better Web Apps

I hope you're enjoying this article.

Get the best content on building better web apps delivered to you.