PHP: Set post/get form submissions to a variable

If you want to take a set of $_POST or $_GET form submissions and set them as variables, you can do this below:

<?php
// loop through each POST variable and set $key which is the name of the field to a variable with the value equal to $value which is the form value
foreach ($_POST as $key=>$value){
   $$key = $value;
}
?>

Therefore, if you have a form of 3 submissons with fields of first_name, last_name, and age with the following values below:

  1. first_name = “John”
  2. last_name = “Doe”
  3. age = 40

You will have pre-set php variables where $first_name = “John”, $last_name = “Doe”, $age = 40. The double dollar sign “$$” makes a variable name value turn into a variable.

Therefore, if you were to print out these variables, in the following script, you would have:

<?php
echo $first_name . "\n";
echo $last_name . "\n";
echo $age . "\n";
?>

This would give you:
John
Doe
40