PHP | Get input name through $_POST[]

php, post, properties

Solution

You can process $_POST in `foreach` loop to get both names and their values, like this:

foreach ($_POST as $name => $value) {
   echo $name; // email, for example
   echo $value; // the same as echo $_POST['email'], in this case
}

But you're not able to fetch the name of property from `$_POST['email']` value - it's a simple string, and it does not store its "origin".

Problem

HTML example: ``` <form method="post" id="form" action="form_action.php"> <input name="email" type="text" /> </form> ``` User fills input field with: dfg@dfg.com ``` echo $_POST['email']; //output: dfg@dfg.com ``` The name and value of each input within the form is send to the server. Is there a way to get the name property? So something like.. ``` echo $_POST['email'].name; //output: email ``` EDIT: To clarify some confusion about my question; The idea was to validate each input dynamically using a switch. I use a separate validation class to keep everything clean. This is a short example of my end result: ``` //Main php page if (is_validForm()) { //All input is valid, do something.. } //Separate validation class function is_validForm () { foreach ($_POST as $name => $value) { if (!is_validInput($name, $value)) return false; } return true; } function is_validInput($name, $value) { if (!$this->is_input($value)) return false; switch($name) { case email: return $this->is_email($value); break; case password: return $this->is_password($value); break; //and all other inputs } } ``` Thanks to raina77ow and everyone else!

Original source