Passing an array using a hidden input tag on a form

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
dickey
Forum Commoner
Posts: 50
Joined: Thu May 16, 2002 8:04 pm
Location: Sydney, Australia

Passing an array using a hidden input tag on a form

Post 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
User avatar
martin
Forum Commoner
Posts: 33
Joined: Fri Jun 28, 2002 12:59 pm
Location: Cambridgeshire

Post 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
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post 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
Post Reply