Page 1 of 1

Passing an array using a hidden input tag on a form

Posted: Tue Jul 02, 2002 7:32 am
by dickey
I wish to pass a variable containing an array using an input tag of type hidden on a form.

1. I create a variable containing the number of results and an array containing product ids.

Code: Select all

$numresults = mysql_num_rows($result);

while ($product = mysql_fetch_assoc($result))
  {
   $idvalue = array($productї"id"]);
   $idarray = array_merge($idarray, $idvalue);
  }
I have tested the array has the values I expect...

2. I include the variables on a form using an input tag type hidden.

Code: Select all

echo "<INPUT type="hidden" name="numresults" value="$numresults">";
echo "<INPUT type="hidden" name="idarray" value="$idarray">";
3. In the response document I attempt to display the values in the array.

Code: Select all

for ($i=0; $i<$numresults; $i++)
echo "$idarray&#1111;$i], ";
Whilst the loop cycles the correct number of times the variable only seems to return the word array and not the values.

Any assistance in resolving this problem will be greatly appreciated.

- Andrew

Posted: Tue Jul 02, 2002 7:55 am
by martin
Use the implode() function to convert your array to a string and then use the explode() function on the receiving script to return to an array.
See http://www.php.net for function help.
Martin

Posted: Tue Jul 02, 2002 8:35 am
by twigletmac
To expand on what Martin said, did you check the source code to see what the hidden variable contained once the page had been loaded? Basically all that gets passed is Array which then becomes the value of $idarray.

So change this:

Code: Select all

while ($product = mysql_fetch_assoc($result)) 
  &#123; 
   $idvalue = array($product&#1111;"id"]); 
   $idarray = array_merge($idarray, $idvalue); 
  &#125;
to this:

Code: Select all

while ($product = mysql_fetch_assoc($result)) &#123; 
    $idarray&#1111;] = $product&#1111;'id'];
&#125;
$idarray = implode('|', $idarray);
Then you should be able to access the variables as an array at the other end by doing:

Code: Select all

$idarray = explode('|', $idarray);
foreach ($idarray as $value) &#123;
    echo $value;
&#125;
If you have very large arrays that you need to pass you might want to consider using sessions instead of hidden fields.

Mac