1

I have the following Array:

$a = array();
$handle = fopen('test.csv','r');
while (!feof($handle)){
    $a = fgetcsv($handle,",");
}
fclose($handle);
echo $a[100];

Accompanied with the following CSV file (test.csv):

100,1245
500,111
600,12

I am getting the following error:

Notice: Undefined offset: 100

I don't understand what I am doing wrong. I have two columns, I want the first column to be the key, and the second column the value. I would then expect to have $a[100] return 1245. What am I missing? Why is this so hard?

EDIT

I want the first column to be the key and the second column to be the value. HOW do I achieve that goal? THAT is the question. Please don't get side tracked...

4
  • 3
    $a[100] does not exist. the array contains 3 items only, so only $a[0], $a[1], and $a[2], are valid. if you're creating a key/value array (whatever that's called in PHP), then use $a["100"] instead. Commented Dec 18, 2014 at 4:23
  • To debug the array use var_dump or print_r for your reference. Commented Dec 18, 2014 at 4:24
  • 100 is not the key, it's a value. Keys will be automatically assigned from 0. Commented Dec 18, 2014 at 4:24
  • @HighCore why does it only contain 3 items? Why does it not contain 3 keys and 3 values? Commented Dec 18, 2014 at 4:24

1 Answer 1

3

You can try

$final  =   array();
foreach($a as $val){
    $var    =   explode(',',$val);
    $final[$var[0]] =   $var[1];
}

echo $final[100];

Output: 1245

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

6 Comments

where does this fall in context of the code that I have already shown above? @Ronser
this line $final[$var[0]] = $var[1]; throws this error Notice: Undefined offset: 1
This is not a solution as I get an undefined offset error.
just use print_r($a); exit; below fclose($handle); and post the result
Array ( [0] => 600 [1] => 12 )
|

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.