niche Posted August 31, 2018 Share Posted August 31, 2018 (edited) 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 August 31, 2018 by niche Link to comment Share on other sites More sharing options...
niche Posted August 31, 2018 Author Share Posted August 31, 2018 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 More sharing options...
niche Posted August 31, 2018 Author Share Posted August 31, 2018 http://php.net/manual/en/language.variables.variable.php (3rd example). Link to comment Share on other sites More sharing options...
dsonesuk Posted August 31, 2018 Share Posted August 31, 2018 Define it as array before the foreach, then use array_push($$wkvar, $val); Link to comment Share on other sites More sharing options...
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now