Passing an array using an HTML form hidden element
Use:
$postvalue = array("a", "b", "c");
foreach($postvalue as $value)
{
echo '<input type="hidden" name="result[]" value="'. $value. '">';
}
And you will get $_POST['result']
as an array.
print_r($_POST['result']);
There are mainly two possible ways to achieve this:
Serialize the data in some way:
$postvalue = serialize($array); // Client side $array = unserialize($_POST['result']; // Server side
And then you can unserialize the posted values with unserialize($postvalue)
. Further information on this is here in the PHP manuals.
Alternativeley you can use the json_encode()
and json_decode()
functions to get a JSON formatted serialized string. You could even shrink the transmitted data with gzcompress()
(note that this is performance intensive) and secure the transmitted data with base64_encode()
(to make your data survive in non-8 bit clean transport layers) This could look like this:
$postvalue = base64_encode(json_encode($array)); // Client side
$array = json_decode(base64_decode($_POST['result'])); // Server side
A not recommended way to serialize your data (but very cheap in performance) is to simply use implode()
on your array to get a string with all values separated by some specified character. On the server side you can retrieve the array with explode()
then. But note that you shouldn't use a character for separation that occurs in the array values (or then escape it) and that you cannot transmit the array keys with this method.
Use the properties of special named input elements:
$postvalue = ""; foreach ($array as $v) { $postvalue .= '<input type="hidden" name="result[]" value="' .$v. '" />'; }
Like this you get your entire array in the
$_POST['result']
variable if the form is sent. Note that this doesn't transmit array keys. However you can achieve this by usingresult[$key]
as name of each field.
Everyone of these methods got their own advantages and disadvantages. What you use is mainly depending on how large your array will be, since you should try to send a minimal amount of data with all of this methods.
Another way to achieve the same is to store the array in a server side session instead of transmitting it client side. Like this you can access the array over the $_SESSION
variable and don't have to transmit anything over the form. For this have a look at a basic usage example of sessions on php.net.