0

I have a CSV file I would like to use as an array in a script.

The CSV is simple:

key1,val1
key2,val2
...

I want to be able to reference the array created like this:

$value = my_csv['key'];

I currently cannot do that because my script shows the index as undefined.

$myArray = array();
$file = fopen('myCSV.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
  array_push($myArray, array($line[0] => $line[1]));
}
fclose($file);
var_dump($myArray['key']);
exit;

I believe this is because I would need to use the numerical index first but I would ideally be able to reference the array in the way I am above.

1 Answer 1

1

The array needs to be created with the key set then, like this

$myArray = array();
$file = fopen('myCSV.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
  $myArray[$line[0]] = $line[1];
}
fclose($file);
var_dump($myArray['key']);

This does assume that there are no duplicates in the key

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

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.