Austin Austin - 19 days ago 5
PHP Question

PHP post all form inputs without creating variables for each

Usually when I use PHP I create a variable and post statement for each form input like so:

$myVar1 = $_POST["formItem1"];
$myVar2 = $_POST["formItem2"];
ect......


I know if i use:

echo $_POST;


I can get all the key and values from the form inputs but I don't know how to use them in a script.

So I guess I have 2 questions:


  1. How do I quickly post all form inputs without creating a variable for each input?

  2. How do I use a posted in a script without having it assigned to a specific variable?


Answer

To simply echo all the inputs, you can use a foreach loop:

foreach ($_POST as $key => $value) {
    echo $value.'<br/>';
}

If you don't want to store them in variables, use arrays:

$data = array();
foreach ($_POST as $key => $value) {
    $data[] = $value;
}

Now, $data is an array containing all the data in $_POST array. You can use it however you wish.