Variable variable with a variable index


#1

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.


#2

{} are your ambiguity solvers.
${$wkvar}[] = $val


#3

is that what they’re called?


#4

Consider this example:

$b = $$a[0];

What am i trying to reference? Is B an array or a string?
Well, I could mean $($a[0]). OR… i could mean ($$a)[0].
And it can get worse, because multidimensional arrays are a thing. ($$a[0][0] … now do i mean either of the two above, or do i attach the second set of braces to the first variable, the second…)
So it just explains explicitly to PHP “Hey, I mean this.”


#5

Thanks.
I found it in the manual:
http://php.net/manual/en/language.variables.variable.php (3rd example).

Missed it
I sure am glad you were around to help!
Have a great weekend!

niche