0

I have a problem with associative-array in PHP – when the source of the arrays is from a text file.

When I write something as follows:

$logins = array('user1' => '1234','user2' => '2345','user3' => '3456');

It all works as expected.

So, I tried to call those arrays from CSV file like that:

$file_handle = fopen("data.csv", "r");
while (!feof($file_handle) ) {
  $line_of_text = fgetcsv($file_handle, 1024);
  if (empty($line_of_text)) { break; }
  $logins = array($line_of_text[0] . '=>' . $line_of_text[1]); /* remove the => and seperate the logins with "," on CSV */
}

It didn't work.

There are a lot close related questions and answers here on SO but I did read and try to implant them without no success. Please Guide me.

Edit: data.csv looks like as follows.

user1,1234;
user2,2345;
user3,3456;
6
  • 1
    To help, would be useful to see an example of (1) The actual CSV you are opening, and (2) the expected / desired output. If data.txt that you've shared above is a string representation of an array, then that will never work (note that you don't actually open data.txt in your code, you open data.csv) Commented Oct 25, 2018 at 15:13
  • php.net/manual/en/function.str-getcsv.php or php.net/manual/en/function.fgetcsv.php Commented Oct 25, 2018 at 15:14
  • @cale_b i update the question. Commented Oct 25, 2018 at 15:26
  • @script47 i got this when i google the question before asking here but i ask it because i didn't understand the examples there (not that php expert - but want to be someday). Commented Oct 25, 2018 at 15:26
  • 1
    you almost good.. just edit this line $logins = array($line_of_text[0] . '=>' . $line_of_text[1]); to $logins[$line_of_text[0]] = $line_of_text[1]; Commented Oct 25, 2018 at 15:49

3 Answers 3

2

You can avoid those loops, conditionals, and fopen()/fclose() messiness:

// read the file into an array
$arr = file("data.csv", \FILE_IGNORE_NEW_LINES | \FILE_SKIP_EMPTY_LINES);

// split each line on the commas
$arr = array_map(fn($v) => explode(",", $v), $arr);

// build an array from the data
$logins = array_column($arr, 1, 0);

Sign up to request clarification or add additional context in comments.

2 Comments

Too many loops, I think you want $logins = array_column($arr, 1, 0); instead of 3 function calls.
Of course! I was just looking at array_column documentation the other day thinking I never use that second argument.
2

As a general rule, it is most appropriate to parse a csv file with a csv parsing technique, but if you like miken22's answer, here's how you optimize/condense it to traverse the data only once. Using sscanf() with %d has the added advantage of trimming the trailing semicolon and casting the number as an integer type value.

Code: (Basic Demo)

var_export(
    array_reduce(
        file("data.csv", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES),
        function($result, $line) {
            sscanf($line, '%[^,],%d', $user, $value);
            $result[$user] = $value;
            return $result;
        },
        []
    )
);

Output:

array (
  'user1' => 1234,
  'user2' => 2345,
  'user3' => 3456,
)

If you don't fear regex and you don't need to cast the values as integers, here is a one-liner (which I will spread over a few lines). (Demo)

var_export(
    preg_match_all(
        '/^([^,]+),(\d+)/m',
        file_get_contents("data.csv"),
        $m
    )
    ? array_combine($m[1], $m[2])
    : []
);

Comments

1

Here is what I think you want

$logins = array();
$file_handle = fopen("data.csv", "r");
while (!feof($file_handle) ) {
  $line_of_text = fgetcsv($file_handle, 1024);
  // At this point, $line_of_text is an array, which will look
  // something like this: {[0]=>'user1',[1]=>'1234'}
  if (empty($line_of_text)) { break; }
  $logins[$line_of_text[0]] = $line_of_text[1];
  // So the line above is equivalent to something like
  // $logins['user1'] = '1234';
}

This would probably also work, though I think it's not something you really want to get into

/* $dataFile = fopen("data.txt", "r"); */
$dataFile = file_get_contents("data.txt");
/* logins = array($dataFile); */
eval('$logins = ' . $dataFile . ';');

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.