Variable Variables With Associative Arrays
Posted: Wed Apr 25, 2012 10:13 am
I am trying to write a function that will allow me to get the $_POST value of a variable, even if it is nested in additional arrays within post. For example, I have a form with the following fields:
As you can see, some will be multi-dimensional while some will not be arrays at all. Easy stuff, but I want to make a function that retrieves that value by only passing the string keys. This is harder than I thought it would be because you have to build the variable name within PHP, not as a string. That is, unless I use variable variables. This is what I am trying to do but I am getting "undefined variable" every time I try it
My function
This outputs
[text]
--> one //this is correct
--> _POST["addresses"]["primary"]["address"] //this is also correct
--> Notice: Undefined variable: _POST["addresses"]["primary"]["address"]..... //this is NOT correct. This variable obviously does exist!
[/text]
So, does anyone know how to get this to work properly or maybe there is a better way to go about doing this instead of crazy variable variables?
Code: Select all
<input type="text" name="address[primary][address]" />
<input type="text" name="address[primary][postalCode]" />
<input type="text" name="address[primary][city]" />
<input type="text" name="name" />
<input type="text" name="country" />
My function
Code: Select all
public function test()
{
$args = func_get_args();
$field = '_POST';
foreach ($args as $arg)
{
$field .= '["'.$arg.'"]';
}
dump($_POST["addresses"]["primary"]["address"]);
dump($field);
dump(${$field});
die();
}
[text]
--> one //this is correct
--> _POST["addresses"]["primary"]["address"] //this is also correct
--> Notice: Undefined variable: _POST["addresses"]["primary"]["address"]..... //this is NOT correct. This variable obviously does exist!
[/text]
So, does anyone know how to get this to work properly or maybe there is a better way to go about doing this instead of crazy variable variables?