Entry
Can I pass a multi-dimensional array from one script to another?
May 4th, 2001 07:07
Erik Dykema, Ben Udall, Leon Atkinson, Dave Martindale, http://www.php.net/manual/en/function.split.php
You can't pass an element multidimensional array like you would one of
a single dimensional array. PHP won't understand the second set of
square brackets. You will have to encode the array element, perhaps by
using some other character. When your script receives the variable,
you must decode it. Here's and example. Suppose you want to pass
$inputMatrix[13][7]. Create a hidden form field like this:
<input type="hidden"
name="inputMatrix_13_7"
value="<? print( $inputMatrix[13][7]); ?>"
>
In the script that receives this value, you'll have to look through all
submitted variables. One way is to use $GLOBALS. Here's an algorithm
with no error checking using PHP4's foreach:
foreach($GLOBALS as $key=>$value)
{
if(substr($key, 0, 11) == "inputMatrix")
{
list($var, $d1, $d2) = split("_", $key);
$inputMatrix[$d1][$d2] = $value;
}
}
---------------------------------------
Here's a second way that might be a bit simpler. PHP has a function
called serialize() which will take a variable (including arrays and
objects) and convert them to a string representation that preserves
type and structure.
// First, serialize the variable into a string
$var_serial = serialize($var);
// Convert characters that might mess up your html to entities
$var_value = rawurlencode($var_serial);
// Create a hidden form element to store the data:
echo '<input type="hidden" name="var" value="'.$out_var.'" />';
Lastly, in the script that recieves the form data, you unserialize the
variable data.
$var = unserialize($var);