Q:

How to build a form with a dynamic number of inputs

I want to call a function that creates a form based button with a dynamic number of hidden inputs.  I'm struggling with it and hope that someone can point me in the right direction.  Here is the background: 
I have a function that I call to return a button with a bunch of hidden inputs which have to be in the $_POST array when the form is submitted.  For example:
<?php
function my_function($var1, $var2) {

    // Initialize the $ctrls variable
    $ctrls = '';

    // Builds the form button
    $ctrls =
    '<form action="" method="post">
        <input type="hidden" name="var1" value="'.$var1.'" />
        <input type="hidden" name="var2" value="'.$var2.'" />
        <input type="submit" value="my button" id="pgn"?>
    </form>';

    return $ctrls;
}
?>

This has been working fine.  However, now I have additional variables I need to begin including, the number of which will vary depending upon the page from which the function is being called.  My intended solution is to create an array to store all the other variables so that the number variables that have to be passed to the function will always be fixed.  For example:
function my_function($var1, $var2, $array)
Then on the page that is calling the function I would define the arrays as follows:
$array = array("var3" => "abc", "var4"=>"def", "var5"=>"ghi");

What I want to do next, which isn't working, is to modify the function as follows:
<?php
function my_function($var1, $var2, $array) {

    // Initialize the $ctrls variable
    $ctrls = '';

    // Builds the form button
    $ctrls =
    '<form action="" method="post">
        <input type="hidden" name="var1" value="'.$var1.'" />
        <input type="hidden" name="var2" value="'.$var2.'" />
        '
        foreach($array as $key=>$value) {
        '
            <input type="hidden" name="'.$key.'" value="'.$value.'" />
        '
        }
        '
        <input type="submit" value="my button" id="pgn"?>
    </form>';

    return $ctrls;
}

The intended result was for the foreach loop to add as many hidden inputs as I had rows in the array. However the page that calls the function won't load when the foreach loop is added to the function.  I also tried to echo the $key and $value variables in the foreach loop, and didn't have any success with that either.
Looking forward to any insights on how to do this.  Strong preference to stick with a solution that uses php and HTML only.  Thanks in advance.

A:

Try this:

// Initialize the $ctrls variable
$ctrls = '';

// Builds the form button
$ctrls =
'<form action="" method="post">
    <input type="hidden" name="var1" value="'.$var1.'" />
    <input type="hidden" name="var2" value="'.$var2.'" />';

    foreach($array as $key=>$value) {
    $ctrls .='
        <input type="hidden" name="'.$key.'" value="'.$value.'" />
    ';
    }
    $ctrls .= '
    <input type="submit" value="my button" id="pgn"?>
</form>';

I hope this will work..

