Search code examples
phphtmlformsdynamic-arrays

Handling two or more select elements in one PHP form


I'm creating a HTML form that had a dynamically-generated list of select inputs. I'd like to cycle through these inputs (in the $_POST array) with a foreach block and make updates in the DB based on the information in each of these inputs. I know I have to name each select input something different so I've appended a unique identifier onto the inputs name (i.e. name="confidenceLevel45").

Is there are a way to preg_match the associative keys in the $_POST array and have a callback to process the values associated with them? Is there another way to do this besides regex'ing the $_POST array keys? I feel like this is a fairly common occurrence in application development but, for some reason, I can't find any answers online. I rather not make an AJAX call and use jQuery to process such a form...

Thank you in advance!


Solution

  • I don't have the reputation to make comments, slightly confused by what you are attempting to do and whether you want to process this client side in jQuery or server side in PHP.

    If you want to process on the server side you could foreach over the $_POST array and match the key value to a switch case or condition:

    foreach ($_POST as $key => value) {
        switch ($key) {
            case 'foo':
              callToFunctionA($value);
              break;
            case 'bar':
              callToFunctionB($value);
              break;
         }
    
         if ($key == 'fizzbuzz') {
             callToFunctionC($value);
         }
    }
    

    Where your cases or conditions match up to the name attributes on your form.