Simple array question

Hi there,

I’m really enjoying learning PHP, but have hit an issue.

I am wanting to build an array, taking a variable as the array key. This is what I have so far:


$source = array(
   [1] => 'old-trafford',
   [2] => 'stamford-bridge',
   [3] => 'anfield'
);
print $source[$fields['fid']->content];

The variable that I wish to take as the array key is $fields[‘fid’]->content. The only possible values of $fields[‘fid’]->content are either 1, 2, 3, so I believe the above should work - so, for example, when the value $fields[‘fid’]->content is 2, stamford-bridge would be returned.

It would be great if someone could let me know where I’m going wrong. Is what I’ve done, the best way to go about the situation?

Thanks

Ben

Yup, the brackets were the culprit.
http://php.net/manual/en/language.types.array.php

Oh, and I meant - 1 not + 1, heh


$source = array(
   1 => 'old-trafford',
   2 => 'stamford-bridge',
   3 => 'anfield'
);
print $source[$fields['fid']->content];

//or let php create the indices for you, starting at 0
$source = array(
   'old-trafford',
   'stamford-bridge',
   'anfield'
);
print $source[$fields['fid']->content + 1];

You may want to verify that $fields[‘fid’]->content contains the value you expect it to. var_dump() is the preferred way to do this.

That works perfectly, thanks.

So, to clarify, the issue was that I enclosed each key in square brackets?

Apologies for posting again - I should have actually checked the result before I last commented.

Although your first solution (manually specifying keys) worked perfectly, your second example doesn’t - for example, when $fields[‘fid’]->content equals 1, then the value of the third key (anfield) is output. Why would this be?