andibakker Posted May 18, 2009 Share Posted May 18, 2009 I am trying to set up an array inside a loop but am getting rather confused. My desired result is to have an array looking like this $defaults['p1'] = '' $defaults['p2'] = '' $defaults['p3'] = '' .... $defaults['p20'] = '' This is my code : for ($i=1; $i<=20; $i++){ $varname = "p{$i}"; $defaults["'" . $$varname . "'"] = ""; } But when I try to view the contents of the array I get Undefined index: p1 in Thanks Link to comment https://forums.phpfreaks.com/topic/158610-solved-variable-variable-inside-an-array/ Share on other sites More sharing options...
premiso Posted May 18, 2009 Share Posted May 18, 2009 Very curious how you are doing this... for ($i=1; $i<=20; $i++){ $varname = "p{$i}"; $defaults[$varname] = ""; } Or even: for ($i=1; $i<=20; $i++){ $defaults["p{$i}"] = ""; } Will do what you are after. You are making it harder then it is. All variables variable does is assign $p1 to equal whatever you put it to: $var = "p1"; $$var = "testing"; echo $p1; Hope that helps you out. Link to comment https://forums.phpfreaks.com/topic/158610-solved-variable-variable-inside-an-array/#findComment-836513 Share on other sites More sharing options...
andibakker Posted May 18, 2009 Author Share Posted May 18, 2009 Of Course !!!! What was I thinking ! Thank you so much ! Link to comment https://forums.phpfreaks.com/topic/158610-solved-variable-variable-inside-an-array/#findComment-836532 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.