Jump to content
niche

using dynamically named array inside foreach loop

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

Share this post


Link to post
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"

 

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...