0

I am setting this array manually:

$schools = array( 'Indiana University'=>array( 'initials'=>'IU', 'color'=>'red', 'directory'=>'indiana' ) ); 

But it won't echo "IU" when I use:

echo $schools[0][0]; 

It does show correctly when I do:

print_r($schools); 

I'm sure I'm messing up something dumb, but I have no idea what and I've been staring at it for hours. This array is actually part of a larger array with multiple universities, but when I trim it down to just this, it doesn't work.

1 Answer 1

2

PHP arrays support two types of keys - numerical and strings.

If you just push a value onto an array, it will use numerical keys by default. E.g.

$schools[] = 'Indiana University'; echo $schools[0]; // Indiana University 

However, when you use string keys, you access the array values using the string key. E.g.

$schools = array( 'Indiana University' => array( 'initials' => 'IU', 'color' => 'red', 'directory' => 'indiana' ) ); echo $schools['Indiana University']['initials']; // UI 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so so much for explaining this part to me, I had missed that part in the docs and examples! I had no idea! It worked immediately when I used the string keys. I will mark this correct in 9 mins when stack overflow allows me to.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.