I have several variables coming from an array in $POST_[‘array’] i wish to make some kind of loop for example foreach that makes, for every value in the variable a variable name of it and assigns the value for it.
For example if i have
$POST_['name'];
$POST_['last'];
$POST_['age'];
$POST_['sex'];
I want the loop to create each variable from the array inside the $_POST with the name of the variable like the following:
$name = 'John';
$last = 'Doe';
$age = '32';
$sex = 'male';
NOTE – The array is coming from a serialized jquery string that puts together all the variables and values in a form into one big string.
Is this possible?
You don’t need a loop, you want extract:
##Cautions and best practices
As noted in the comments this forces all parameters in the
$_POSTarray into the current symbol space.In global space
The code above illustrates the problem as shown in this answer — some pretty dangerous things can be overwritten in the global space.
Inside a function
Inside a function, as the first line, no harm done.
Important note: You might think since
$_SERVERis a super global, that this exploit could happen inside a function as well. However, in my testing, on PHP Version 5.3.4, it is safe inside a function — neither$_SERVER,$_POST,$_GET,$_SESSION, or presumably other superglobals, could be overwritten.With options
You can also use extract with extract_type options that do not overwrite.
The best option to use, in my opinion, is simply to prefix all variables from extract:
That way you don’t have the overwrite problem, but you also know you got everything from the array.
##Alternate – looping w/ conditional
If you wanted to do this manually (but still dynamically), or wanted to conditionally extract only a few of the variables, you can use variable variables:
(The example condition I’ve used is an overwrite prevention.)