Html form hidden element is used to pass information which is not visible to the user but used internaly by underlying scripts. For example the status of the process or step of multi step form submission. PHP array is an important language structure used in manipulation of multiple values associated with single object. Sometimes it is required to pass these values accross the pages between browser and the server. Following method can be used to pass PHP Arrays using html form hidden elements.
Using individual array element
This method uses seperate hidden element for each element in array. This can be done by following method.
foreach ($my_array as $key => $value)
{
echo ‘<input type=hidden name=”my_array[]” value=”‘.htmlspecialchars($value).'”>’;
}
This will generate an array in html form. And when submitted can be accessed by form handling PHP script using following code.
$my_array = $_POST[‘my_array’];
Combining all array elements in one value to hidden element
In this method all elements in an array are combined in single value using implode() PHP function. implode() will return a string combining all the array elements in the same order, seperated by given string. Then this combined value can be passed in html form hidden element. See below.
$single_value = implode(“,”, $my_array);
echo ‘<input type=hidden name=”single_value” value=”‘.htmlspecialchars($single_value).'”>’;
And when submitted the array can be retreived using explode() PHP function. explode() will return an array by spliting the string using the given seperator. See code below.
$my_array = explode(“,”,$_POST[‘single_value’]);
Posted by V.HPatel