Page 1 of 1

Using variable as array key

Posted: Wed Apr 30, 2008 12:27 pm
by seodevhead
I have a couple array variables like so:

Code: Select all

$var = array ('FL' => 'florida', 'WY' => 'wyoming');
..and I want to be able to use a non-array variable to reference the proper key... example:

Code: Select all

$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...

Code: Select all

// Which one is right?
echo $var[$userState];
echo $var["$userState"];
echo $var['".$userState."'];
// etc etc.
Thank you for any help.

Re: Using variable as array key

Posted: Wed Apr 30, 2008 1:39 pm
by andym01480

Code: Select all

$userState = 'FL';
 
echo $var[$userState];  // should output florida.
Didn't you try it and see that it did work?

Re: Using variable as array key

Posted: Fri May 02, 2008 1:50 pm
by RobertGonzalez
This is an excellent opportunity to try something for the first time.

PS You are totally on the right track. In fact you even answered your own question whilst asking it. :wink: