Jump to content

[SOLVED] variable variable inside an array


andibakker

Recommended Posts

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

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.