Forum Moderators: coopster

Message Too Old, No Replies

Using Variable As Array Key

How to embed a variable into the key of an array.

         

apacheMan

5:56 pm on Apr 30, 2008 (gmt 0)

10+ Year Member



I have a couple array variables like so:

$var = array ('FL' => 'florida', 'WY' => 'wyoming');

..and I want to be able to use a non-array variable to reference the proper key... example:

$userState = 'FL';

echo $var[$userState]; // should output florida

But I'm unsure how I actually "embed" that $userState variable within the array variable. Do I need to use double quotes? Single quotes? No quotes? etc.

ie...

// Which one is right?
echo $var[$userState];
echo $var["$userState"];
echo $var['".$userState."'];
// etc etc.

Thank you for any help.

Little_G

6:02 pm on Apr 30, 2008 (gmt 0)

10+ Year Member



Hi,

echo $var[$userState];
will work fine.

Andrew