Entry
How can I use an array as a form variable?
Can I pass an array from one script to another?
How can I use a multi-dimensional array as a form variable?
Jul 28th, 2000 09:44
Ben Udall, Rada Eulen, Fred Isler, Nathan Wallace, Onno Benschop, Leon Atkinson, http://www.php.net/manual/function.serialize.php
PHP does let you collect multiple values from checkboxes in a form using
a single dimensional array. For example:
<input type="checkbox" name="foo[]" value="foo">
<input type="checkbox" name="foo[]" value="bar">
But you can't use a multi-dimensional array as the form name. The
language parser in PHP3 doesn't understand ][ inside a variable name, so
you'll have to think of some other naming scheme (like
variable[$mem_id::$article]) and then parse it on the receiving
end.
Use implode() and explode() to pass the contents of a single
dimensional
array from one page/script to another using a form:
First, implode() an array of strings on the first page. Example:
$yourarray[0] = "foo";
$yourarray[1] = "bar";
$string = implode("|", $yourarray); //$string looks like this: foo|bar
// Send $string on to the next page:
echo "<input type=hidden name=string value=$string>";
On the second page/script, explode() $string to get your array back:
$seconddarray = explode("|", $string);
---------------------------------------
Here's another way that should let you pass arrays (including multi-
dimensional ones), and objects. PHP has a function called serialize()
which will take a variable (including arrays and objects) and convert
them to a byte-stream representation that preserves type and structure.
// First serialize the variable
$serial_var = serialize($var);
// Next use rawurlencode() so certain characters
// in $serial_var won't mess up your html:
$out_var = rawurlencode($serial_var);
//Then you create a hidden form element to store the data:
print("<INPUT type=\"hidden\" name=\"var\" value=\"$out_var\">\n");
Lastly, in the script that recieves the form data, you reverse
everything:
$var = unserialize(rawurldecode($var));