reading from a file to associative array in php

It's pretty straight forward. First read the file line-by-line (e.g. see the file function which does this already). Then parse each line by splitting it at the first space (see explode), use the first part as key and the second part as value:

$array = array();
foreach (file($myFile) as $line)
{
    list($key, $value) = explode(' ', $line, 2) + array(NULL, NULL);

    if ($value !== NULL)
    {
        $array[$key] = $value;
    }
}

If your parser needs to be more specific, change it according to your needs. There are a lot of string functions with PHP that can be used for more differentiated parsing, like sscanf or regular expressions.

Another common method is to extend from SplFileObject, it allows to encapsulate the data-aquisition inside an iterator so you can better differentiate between the place where the data is used and where it is taken from. You can find an example in another answer:

  • PHP - Process CSV Into Array With Column Headings For Key

$myFile = "codes.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
$assoc_array = array();
$my_array = explode("\n", $theData);
foreach($my_array as $line)
{
    $tmp = explode(" ", $line);
    $assoc_array[$tmp[0]] = $tmp[1];
}
fclose($fh);

// well the op wants the results to be in $codes
$codes = $assoc_array;

Tags:

Php