Jump to content

using dynamically named array inside foreach loop


niche

Recommended Posts

This works:

$names = 
array(
	array("name"=>"tom","gender"=>"m"),
	array("name"=>"jane","gender"=>"f"),
	array("name"=>"steve","gender"=>"m"),
	array("name"=>"mary","gender"=>"f"),
	array("name"=>"renae","gender"=>"f")
);	

$num = 30;
$wkvar = 'wk' . $num;

foreach ($names AS $val) {
	
	$wk30[] = $val;
	
	//$$wkvar[] =  $val;
	
}

var_dump($wk30);

this doesn’t and gives me this error, “Fatal error: Cannot use [] for reading”, (goggle hasn’t helped me):

$names = 
array(
	array("name"=>"tom","gender"=>"m"),
	array("name"=>"jane","gender"=>"f"),
	array("name"=>"steve","gender"=>"m"),
	array("name"=>"mary","gender"=>"f"),
	array("name"=>"renae","gender"=>"f")
);	

$num = 30;
$wkvar = 'wk' . $num;

foreach ($names AS $val) {
	
	//$wk30[] = $val;
	
	$$wkvar[] =  $val;
	
}

var_dump($wk30);

I need to use the 2nd (variable variable) approach. What am I doing wrong?

I tried adding a dynamic index unsuccessfully.

Edited by niche
Link to comment
Share on other sites

found the notation:

${$wkvar}[$i] =  $val;

If this has a name, pls let me know so I can get a ref?

 

stumbled on to by finally googling: "dynamic naming arrays  php"

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...