Using variable as array key

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
seodevhead
Forum Regular
Posts: 705
Joined: Sat Oct 08, 2005 8:18 pm
Location: Windermere, FL

Using variable as array key

Post 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.
User avatar
andym01480
Forum Contributor
Posts: 390
Joined: Wed Apr 19, 2006 5:01 pm

Re: Using variable as array key

Post by andym01480 »

Code: Select all

$userState = 'FL';
 
echo $var[$userState];  // should output florida.
Didn't you try it and see that it did work?
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Re: Using variable as array key

Post 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:
Post Reply