Read or Import CSV to an Array in PHP Code Example

Import CSV to an array using PHP's fgetcsv function. The array is associative so you can access values by the column heading.

By Tim Trott | PHP Tutorials | October 31, 2013

This PHP function will import CSV and convert it to an associative array based on the column headings in the first row. To use, simply call the function with a valid filename as the only parameter. The function will return an associative array of the imported CSV file contents.

The file you want to import CSV to an array object must have column headings as the first row since these are used to create the associative array elements.

Import CSV to Array with PHP

php
<?php

function ImportCSV2Array($filename)
{
    $row = 0;
    $col = 0;
    
    $handle = @fopen($filename, "r");
    if ($handle) 
    {
        while (($row = fgetcsv($handle, 4096)) !== false) 
        {
            if (empty($fields)) 
            {
                $fields = $row;
                continue;
            }
            
            foreach ($row as $k=>$value) 
            {
                $results[$col][$fields[$k]] = $value;
            }
            $col++;
            unset($row);
        }
        if (!feof($handle)) 
        {
            echo "Error: unexpected fgets() failn";
        }
        fclose($handle);
    }
    
    return $results;
}

Example Usage

php
<?php

/ Import CSV to an Array
$filename = "test.csv";
$csvArray = ImportCSV2Array($filename)

foreach ($csvArray as $row)
{
    echo $row['column1'];
    echo $row['column2'];
    echo $row['column3'];
}

What is Happening?

This function takes each line of the CSV import file and runs it through PHP's fgetcsv  function. This function is similar to fgets except that fgetcsv parses the line it reads for fields in CSV format and returns an array containing the fields read. The array is an indexed array, with the first item at 0, the second at 1 and so on.

To get the associative array, the first row of data is used as the column headings, and then a loop runs over each item in the array from fgetcsv and inserts it against the column heading.

The method of using associative arrays is far better than an indexed array, as it can often be confusing, cause errors trying to remember what piece of data is at any given numerical index, and code maintenance is often a minefield. If a new column is added to the data, you have to update all the indexes where that array is used. With an associative array, you access data via a name, so it does not matter what order the data is read in or how many columns are inserted, that name will remain constant.

Was this article helpful to you?
 

Related ArticlesThese articles may also be of interest to you

CommentsShare your thoughts in the comments below

If you enjoyed reading this article, or it helped you in some way, all I ask in return is you leave a comment below or share this page with your friends. Thank you.

This post has 5 comment(s). Why not join the discussion!

We respect your privacy, and will not make your email public. Learn how your comment data is processed.

  1. MA

    On Monday 10th of February 2020, Mark said

    Glad I bumped into this on my google search. I had two lists of symlinks, with 24 and 32 links to insert in two directories. As I'm on a virtual host with no access to the shell, I wanted a PHP script to do what bash would do from the command line. With this snippet I was able to loop through my lists and create the two sets of symlinks in micro milliseconds if I don't count the time spent typing the address in the browser.

    Thank you.

  2. GA

    On Friday 26th of February 2016, Gary said

    Hi, great function! How would you start reading at say the 300th row? I'm trying to work this out but am not an expert in PHP, can it be done within your function? Thanks in advance!

    1. Tim Trott

      On Saturday 27th of February 2016, Tim Trott  Post Author replied

      Just a quick idea, you could check the counter before processing the row. Something similar to this should work:

      php
      while (($row = fgetcsv($handle, 4096)) !== false) 
      {
        if (empty($fields)) 
        {
          $fields = $row;
          continue;
        }
       
        / start at row 300. $col is 0 indexed
        if ($col > 299)
        {
          foreach ($row as $k=>$value) 
          {
            $results[$col][$fields[$k]] = $value;
          }
        }
      
        $col++;
        unset($row);
      }
  3. NI

    On Friday 6th of February 2015, Nick said

    Many thanks, you saved the day.

  4. ST

    On Tuesday 4th of November 2014, Steve said

    Thanks Tim, used it today, works great!