How to initialize an associative array in a while loop?

Now I am doing a simple thing, I will read from a CSV file, this column A contains code such as "EN", column B contains the specific name "English", etc., and I want to read them into an associated array.

My current action looks like this:

  $handle = fopen("Languages.csv","r") or die("EPIC FAIL!");

  $languageArray = array(
  while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) 
  {
              $row[0] => $row[1],
  }
  )

But he really complains about my syntax, so I'm just wondering if there is a way to initialize my associated array by getting all the lines of my csv file and putting the first row (from column A) as the key, the second row (from column B) as the value ?

Thank.

+3
source share
4 answers

Initialize first as empty:

$languageArray = array();

while :

while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) 
{
    $languageArray[$row[0]] = $row[1];
}

PHP-/ , , , , , .

+9

:

$languageArray = array();
while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) 
{
          $languageArray[$row[0]] = $row[1];
}
+3

First create an array:

$myArray = array();

Then add the key => value binding:

$myArray[$key] = $value;

In your case, it should be something like (in a loop):

$myArray[$row[0]] = $row[1];
+2
source

How about the first initialization of an empty array, which will later be filled with your data:

$languageArray = array();

Then, going through the CVS file line by line, using each line to put data into this array:

$handle = fopen("Languages.csv","r") or die("EPIC FAIL!");
while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
    // $row[0] is the first column,
    // $row[1] is the second one.
    $languageArray[$row[0]] = $row[1];
}


You cannot declare an array using code inside its initialization: you must proceed in two steps.

+2
source

All Articles