Simple multidimensional array index problem

Hi: I am trying to generate and access a simple array of students and grades. I can get the array built (eventually I will populate it via a form), but I don’t see how to access the individual elements.

I tried this approach:
[php]$grades=array(array(‘id’=>201256, ‘name’=>‘Frank Thomas’, ‘scores’=>array(90,97,95,85)),
array(‘id’=>201297, ‘name’=>‘Anne West’, ‘scores’=>array (98,75,90,85)));
print_r($grades);
echo $grades[0][0]." is ". $grades[0][1];[/php]

The print_r works fine, but I get an “undefined index” error on the echo line. (I want it to print out “201256 is Frank Thomas”)

I’d really like to do something like $grades[0][‘id’] etc, but obviously those give me errors, too.

Thanks for any help.

Ed

i think your echo should be

[php] echo $grades[‘id’]." is ". $grades[‘name’];[/php]

Thanks.

Unfortunately, that returns the same error, “Undefined index” and prints just “is”.

Those should work
[php]
$grades[‘0’][‘id’]
$grades[‘0’][‘name’]
[/php]

Try to use
[php]var_dump($grades);[/php]

Thanks. This works, and extends to [php]echo $grades[‘0’][‘id’]." is ". $grades[‘0’][‘name’] . " whose grade on the third exam was ". $grades[‘0’][‘scores’][‘2’];[/php] which as my next step.

Just to help me understand, can you explain why I need to put ’ ’ around what seems to me to be a numeric index? Would I need to do it if all my indices were numeric?

Thanks again. Ed

They need to be put on all index’s numeric or string.
They changed it in one of the php5’s can’t remmeber off the top of my head why.
Still you can carry on coding now you learnt something new. ;D

Thanks. I did learn something.
Also, now I was able by experimentation to see that if I put a variable inside the [], I don’t need the ’ '.

Sponsor our Newsletter | Privacy Policy | Terms of Service