So I have a CSV file that looks like this:

12345, Here is some text
20394, Here is some more text

How can I insert this into an array that looks like so

$text = "12345" => "Here is some text",
        "20394" => "Here is some more text";

This is what I currently had to get a single numerical based value on a one tier CSV

      if ($handle = fopen("$qid", "r")) {

          $csvData = file_get_contents($qid);
          $csvDelim = "\r";

          $qid = array();
          $qid = str_getcsv($csvData, $csvDelim);

      } else {

          die("Could not open CSV file.");


Thanks for the replies, but I still see a potential issue. With these solutions, wouldn't the values store in this way:

$array[0] = 12345
$array[1] = Here is some text 20394
$array[2] = Here is some more text

If I tried this on the example csv above, how would the array be structured?


Do comma's occur within the text?

Written by Sjoerd

Your delimiter should be ',', not "\r"

Written by meagar

What you cannot be done, computers are not capable of such black magic. You'd need to write several thousand lines of code in assembler and have at least 16 cores in your computer to even attempt it.

Written by MooGoo

Accepted Answer

You can use fgetcsv() to read a line from a file into an array. So something like this:

$a = array();
$f = fopen(....);
while ($line = fgetcsv($f))
    $key = array_shift($line);
    $a[$key] = $line;
Written by Hollance
This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the community.
It is licensed under cc-wiki