Skip to content
Home » Read CSV Files to Associative Array with Headers PHP Examples

Read CSV Files to Associative Array with Headers PHP Examples

Summary

There are 2 ways you can convert CSV to associative arrays in PHP. The modern approach would be to use the array_map, array_filter, & array_combine functions. The older legacy approach uses loops to loop through the content. The first method is preferred in modern applications.

PHP Code to Read a CSV File With Headers into an Associative Array

  1. Open the csv file and get the contents with the array_map function.
  2. Use the array_shift method to get your header row.
  3. Create a PHP array to store your CSV body content.
  4. Loop through the remaining rows with a foreach loop.
  5. Check to make sure the loop content is not empty.
  6. Push a new element to the CSV array that you created using the array_combine function.
  7. Print and test your results.
  8. Continue processing as required.
<?php
    //Map lines of the string returned by file function to $rows array.
    $rows   = array_map('str_getcsv', file('employees.csv'));
    //Get the first row that is the HEADER row.
    $header_row = array_shift($rows);
    //This array holds the final response.
    $employee_csv    = [];
    foreach($rows as $row) {
        if(!empty($row)){
            $employee_csv[] = array_combine($header_row, $row);
        }
    }
 
    print_r($employee_csv)

Have you tried any of the following highly relevant Pluralsight PHP Courses?

We love Pluralsight because it has thousands of high-quality course content and is extremely affordable. You don’t have to pay for individual courses. It’s a really small monthly membership and you get access to the entire catalog. You can track and review all of your progress and also obtain additional certifications.

Courses

  • PHP Design Patterns
  • PHP: The Big Picture
  • PHP 8: Web Application Security
  • High-Performance PHP
  • Object-Oriented PHP

Learning Paths:

  • PHP Development Fundamentals

Pluralsight Free Trial

Curious about Pluralsight but not ready to commit? We understand. We were able to get a free trial for you to test-drive and see all of their courses. Click on the link below

Try a Pluralsight free trial for 7 days!

CSV PHP Code Examples and Learning Path

Comma-separated files or CSVs are popular for book-keeping and persisting data. Although large-scale applications use cloud storage or databases. However, that doesn’t mean CSVs are out of the league now. We use them often for data entry and maintaining records for simple transactions.

convert csv to associative array PHP

A useful feature of PHP is working with CSV files. We have already seen converting associative arrays to CSV. In this article, we’ll see how to read and convert CSV to associative array PHP. Once you have mapped a CSV file to an associative array, a range of data transformations could be possible. So, let’s jump into the main topic without further ado.

Read CSV files to a PHP associative array

Disclaimer

This approach to read CSV files into PHP associative arrays would work in PHP 5 >= 5.3.0, PHP 7, PHP 8. If you’re not using these versions, then perhaps the second option would work for you.

Simplest way to map CSV to associative arrays in PHP

Here’s the simplest way to map CSV to associative arrays in PHP. We have a CSV file with employees data. We need to convert this CSV to associative array PHP.

convert csv to associative array PHP

Let’s look at the code and output and then break down the flow to enhance its understanding.

The PHP script to load the CSV file into the array

<?php
    //Map lines of the string returned by file function to $rows array.
    $rows   = array_map('str_getcsv', file('employees.csv'));
    //Get the first row that is the HEADER row.
    $header_row = array_shift($rows);
    //This array holds the final response.
    $employee_csv    = array();
    foreach($rows as $row) {
        if(!empty($row)){
            $employee_csv[] = array_combine($header_row, $row);
        }
    }
 
    print_r($employee_csv)

Output results of converting CSV to array

Array
(
    [0] => Array
        (
            [Id] => 1
            [Name] => Anna
            [Age] => 30
            [Salary] => 20000
            [Department] => Finance
        )

    [1] => Array
        (
            [Id] => 2
            [Name] => Adam
            [Age] => 25
            [Salary] => 15000
            [Department] => IT
        )

    [2] => Array
        (
            [Id] => 3
            [Name] => Bob
            [Age] => 32
            [Salary] => 25000
            [Department] => Finance
        )

    [3] => Array
        (
            [Id] => 4
            [Name] => Cara
            [Age] => 20
            [Salary] => 12000
            [Department] => Logistics
        )

    [4] => Array
        (
            [Id] => 5
            [Name] => Daniel
            [Age] => 28
            [Salary] => 27000
            [Department] => Engineering
        )

    [5] => Array
        (
            [Id] => 6
            [Name] => Franklin
            [Age] => 25
            [Salary] => 20000
            [Department] => Quality Assurance
        )

    [6] => Array
        (
            [Id] => 7
            [Name] => Gorge
            [Age] => 21
            [Salary] => 15000
            [Department] => IT
        )

    [7] => Array
        (
            [Id] => 8
            [Name] => Kylie
            [Age] => 20
            [Salary] => 10000
            [Department] => Engineering
        )

    [8] => Array
        (
            [Id] => 9
            [Name] => Ivan
            [Age] => 23
            [Salary] => 12000
            [Department] => Logistics
        )

    [9] => Array
        (
            [Id] => 10
            [Name] => James
            [Age] => 25
            [Salary] => 20000
            [Department] => Quality Assurance
        )

)

The mapping from CSV to associative arrays in PHP has been done with a few lines of code that we’re going to debunk now.

Break Down

Here’s a flow chart of how the logic flows. We will see how all these functions work together to get the task done.

  1. The array_map function gets a callback function str_getcsv and file function as the second argument. 
    • The file function reads the entire CSV file as a string.
    • The array_map function uses the callback function str_getcsv to process the string line by line and convert it into an array.
  2.  After step 1, we have an array that has all the comma-separated entities as individual values. We run the array_shift to get the header row.
  3. We iterate over the remaining array values, and by using array_combine, it maps each row to the header.
  4. Finally, the CSV to associative array PHP maps as shown in the output.

The code is rather simple to comprehend if you know these functions. It is recommended to gain familiarity with these functions by following the official PHP documentation page links.

Read and convert CSV to associative array with headers full PHP Example

We’ll see an example here that would also run equally well of PHP version 4 and greater. This example would have more code than the previous one because many latest functions have been replaced with compatible functions, and certain parts of code have been reduced to nested foreach loops to get the task done.

<?php
    //Map lines of the string returned by file function to $rows array.
    $rows   = array_map(function($employee){return explode(",",$employee); }, file('employees.csv'));
    //Get the first row that is the HEADER row.
    $header_row = array_shift($rows);
    //This array holds the final response.
    $employee_csv    = array();
 
    foreach($rows as $row) {
        if(!empty($row)){
            $temp = [];
            //Loop through the individual attributes in the row and map it to a corresponding header.
            for($i =0; $i < count($row); $i++)
            {
                $temp[$header_row[$i]] = $row[$i];
            }
 
            //Push the row to the employees array.
            array_push($employee_csv,$temp);
            
        }
    }
 
    print_r($employee_csv)
?>

The output and the flow of the code remain the same. So, we won’t be re-explaining the whole thing. The difference here is that some functions have been replaced with more compatible code. You can try it to figure it out by going through the breakdown in the previous section.

CSV to PHP Associative Arrays with Headers

We have seen how to read and convert CSV to associative arrays in PHP. The first option is the simplest one, but some functions used there are incompatible with PHP versions less than 5. So, the second option deals with incompatibility and uses alternatives to get around the compatibility issue. We hope you’ve learned about converting CSV to associative array PHP.

Want to explore more useful PHP tutorials?

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

Search for multiple values in PHP array

How to filter array of objects by value in PHP

How to filter array of objects by key in PHP