0

Sorry for the question but, I don't know how to solve my problem.
I've got a form with predefined input names in a standard form and I have other inputs with any random names, for example:

<form action="">
    <!-- required inputs -->
    <input type="text" name="name" value="Ian" />
    <input type="text" name="surname" value="Dope" />
    <input type="tel" name="phone" value="782910456" />
    <input type="tel" name="comment" value="" />
    <!-- optional inputs -->
    <input type="hidden" name="conact_amount" value="1" />
    <input type="hidden" name="value1" value="2" />
    <input type="hidden" name="other_filed" value="3" />
    <input type="hidden" name="different_name" value="4" />
</form>

In the above form, the required inputs will have the same name, whereas the optional inputs can be any arrangements of different names.

I want to leave the required fields as they are, but the optional fields - that I don't know the names of - need to be placed in an array called comment.

JustCarty
  • 3,839
  • 5
  • 31
  • 51
Digital Legend
  • 149
  • 1
  • 13
  • 8
    No, you lost me. – Aniket Sahrawat Apr 23 '18 at 08:18
  • 1
    What are you going to do with those inputs you don't know the names of? It seems strange to let a form post what ever fields it wants. Anyway, you could iterate through the fields and check the name to see if it is a "required" field or not. Then you can just do what you want with them. – M. Eriksson Apr 23 '18 at 08:19
  • Also, if they're required, consider adding the HTML5 required attribute to the inputs? – JustCarty Apr 23 '18 at 08:21
  • You can dynamically add the inputs to the form using JavaScript before submitting, and use `elem.setAttribute("name", "input-name-here");` to add a custom name. There's good documentation on how to do this at [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement). – jknotek Apr 23 '18 at 08:23
  • 1
    Also, take a look at [this answer](https://stackoverflow.com/questions/6334830/php-possible-to-automatically-get-all-posted-data) if you're asking for help on the back end. – jknotek Apr 23 '18 at 08:26

1 Answers1

0

What about iterating over the posted array as so:

$required = ['name', 'surname', 'phone', 'comment'];
$comment = array();
foreach ($_POST as $key => $value) {
    if (!in_array(strtolower($key), $required)) {
        $comment[$key] = $value;
    }
}

This assumes that you know the names of the required fields ahead of time.
It simply loops through the posted array, determines if it was a required field with a set name attribute and, if it isn't, it will add it to a new array - $comment.

This, of course, assumes that my understanding of your question is correct.

JustCarty
  • 3,839
  • 5
  • 31
  • 51