Anti-Moronic Posted May 20, 2009 Share Posted May 20, 2009 Title says it all really. I have no idea if I am doing this correctly or effectively. Here's my array: <?php $arr = array( "key1" => "val1", ) //To add a key => val I use: $arr['key'] = "val"; ?> That works fine, but I can't assign a key=>val unless the key is literal and within single quotes. For example, this doesn't work: $key=key2; $arr[$key] = "val"; Any advice on how I should be going about this. Maybe a better way of adding elements to my array (while being able to set custom keys). Thanks. Link to comment https://forums.phpfreaks.com/topic/158863-having-trouble-with-array-adding-key-value-when-key-is-variable/ Share on other sites More sharing options...
pdkv2 Posted May 20, 2009 Share Posted May 20, 2009 if you want to add the array elements dynamically () the the second approach $arr['key'] = "val"; is better Link to comment https://forums.phpfreaks.com/topic/158863-having-trouble-with-array-adding-key-value-when-key-is-variable/#findComment-837898 Share on other sites More sharing options...
Anti-Moronic Posted May 20, 2009 Author Share Posted May 20, 2009 That's not what I'm trying to do. Thanks any way. I'm trying to assign the key dynamically. Link to comment https://forums.phpfreaks.com/topic/158863-having-trouble-with-array-adding-key-value-when-key-is-variable/#findComment-837900 Share on other sites More sharing options...
pdkv2 Posted May 20, 2009 Share Posted May 20, 2009 yes you can assign key dynamically as $k="yourkey"; $ar[$k] = "value"; Link to comment https://forums.phpfreaks.com/topic/158863-having-trouble-with-array-adding-key-value-when-key-is-variable/#findComment-837904 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.