6

I have a file codes.txt with records like this

USA 0233
JPN 6789
TUN 8990
CDN 2345

I want to read these content of the file to an associative array like this.

$codes["USA"] = 0233;
$codes["JPN"] = 6789;
$codes["TUN"] = 8990;
$codes["CDN"] = 2345;

this is the code that opens the file for writing. I need help in the array part. thks

$myFile = "codes.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
fclose($fh)
mickmackusa
  • 37,596
  • 11
  • 75
  • 105
karto
  • 3,278
  • 8
  • 41
  • 66

3 Answers3

10

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:

Community
  • 1
  • 1
hakre
  • 184,866
  • 48
  • 414
  • 792
4
$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;
mrid
  • 5,584
  • 5
  • 24
  • 62
0

There is an optimal way of doing this than any of these answers. You can use file_get_contents and array_walk functions to cut the things very short.

$allCases = explode("\r\n", file_get_contents("myfile.txt")); 
$myList = array();    
array_walk($allCases, "step", $myList); 

function step($val, $key, &$arr) {
    $aCase = explode(" ", $val);
    $arr[$aCase[0]] = $aCase[1]; 
}

This way you don't need a for loop or a file handler.

Beware of the delimiter "\r\n" since this could be platform dependent in this case.

Charlie
  • 21,138
  • 10
  • 54
  • 85