spaghettio05 Posted October 25, 2011 Share Posted October 25, 2011 Hi all, I can't seem to designate an array key by using a variable and I was wondering if this is possible. I'm looking to do something like this: <?php $key = "apple"; $arr = array($key => "fruit"); ?> Any suggestions would be appreciated! Quote Link to comment https://forums.phpfreaks.com/topic/249807-assigning-array-key-name-by-variable/ Share on other sites More sharing options...
jcbones Posted October 25, 2011 Share Posted October 25, 2011 To answer your question: variable variables <?php $key = "apple"; $arr = array($$key => "fruit"); ?> Although, I prefer keys and values like: <?php $arr = array('fruit' => 'apple'); echo 'Hmmm, what kind of fruit do we have? Oh an, ' . $arr['fruit'] . '!'; ?> Quote Link to comment https://forums.phpfreaks.com/topic/249807-assigning-array-key-name-by-variable/#findComment-1282218 Share on other sites More sharing options...
Buddski Posted October 25, 2011 Share Posted October 25, 2011 To answer your question: variable variables <?php $key = "apple"; $arr = array($$key => "fruit"); ?> This will throw an undefined variable error. The OP's original code was correct, I suspect the issue is in the retrieval. $key = "apple"; $arr = array($key => "fruit"); print_r($arr); // Output: Array ( [apple] => fruit ) Quote Link to comment https://forums.phpfreaks.com/topic/249807-assigning-array-key-name-by-variable/#findComment-1282219 Share on other sites More sharing options...
spaghettio05 Posted October 25, 2011 Author Share Posted October 25, 2011 Oops, yes, my original code is correct (found the mistake in my other code from which it came). Thanks for the replies! Quote Link to comment https://forums.phpfreaks.com/topic/249807-assigning-array-key-name-by-variable/#findComment-1282220 Share on other sites More sharing options...
jcbones Posted October 25, 2011 Share Posted October 25, 2011 Yes, buddski, you are correct. Didn't think that one through. Quote Link to comment https://forums.phpfreaks.com/topic/249807-assigning-array-key-name-by-variable/#findComment-1282239 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.