9

I am now doing a simple thing, I am going to read from a CSV file, that column A contains code such as "EN", column B contains specific name "English"..etc., and I want to read them into an associate array.

My current doing is like this:

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

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

But it actually complains about my syntax, so I am just wondering if there is a way to initialize my associate array by getting all the rows of my csv file, and put the first string(from column A) as the key, the second string(from column B)as the value?

Thanks.

0

4 Answers 4

16

Initialize it as empty first:

$languageArray = array();

Then populate it using a separate while loop like this:

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

PHP arrays/hashes have no fixed size and are thus mutable in all kinds of ways, so even if you initialize them as empty you can populate them however you want later.

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

Comments

4

First create the array:

$myArray = array();

Then to add a key => value binding:

$myArray[$key] = $value;

In your case, this should be something like (in the loop):

$myArray[$row[0]] = $row[1];

Comments

3

Do it more conventionally:

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

Comments

2

What about first initializing an empty array, that will later be populated with your data :

$languageArray = array();

Then, going through the CVS file line by line, using each row to put data into that 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 it's initialization : you have to act in two steps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.