• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

PHP: Array as value of hidden form?

Armitage

Banned
I need to send an associative array through a hidden form field.
Are there library functions that can do this for me?
pack/unpack & serialize/unserialize don't seem to be what I need.
Thanks
 
I wrote a post, came up with an alternative solution, and then deleted the post... I think I have something you can use.

Originally I didn't think this could be done, and I had suggested using a database and serializing the array into a database record, with a unique identifier, and passing the identifer in the hidden field so you could unserialize the array.

Instead of doing that, if you serialize the array, and make the contents of the hidden field equal to the serialized result of the array, you should be able to unserialize from that form field on the next page and get your array back. Serializing an object makes it into a string, so you shouldn't have any problems putting that into a hidden form field, unless there is some limitation on the hidden form field I am unaware of. Of course, there may be a limit on the size of the array that can be passed using this method.

 
Ok, serialize does work, but you also need to encode it to escape the special characters, etc.

Here's how I got it to work:

On the page with the hidden form field:

$data = serialize($data);
$data = rawurlencode($data);

then pass $data through the hidden form field

on the target page:

$data = $_POST['data'];
$data = rawurldecode($data);
$data = unserialize($data);

Thanks!
 
Can't you just use multiple hidden form fields?

<input type="hidden" name="myarray[keyone]" value="my value" />
<input type="hidden" name="myarray[keytwo]" value="my second value" />
<input type="hidden" name="myarray[keythree]" value="the third value" />
 
I had a feeling it might have to be encoded, but I wasn't sure if there were any special characters in the serialization stuff. Atleast it works, and I've learned something as well. 🙂
 
Originally posted by: Superwormy
Can't you just use multiple hidden form fields?

<input type="hidden" name="myarray[keyone]" value="my value" />
<input type="hidden" name="myarray[keytwo]" value="my second value" />
<input type="hidden" name="myarray[keythree]" value="the third value" />

You could, but it gets tedious & error prone. And you'd have two more places to fix every time you add to or change the array.
And you may have a case where you want to use the same code for a variety of input arrays.
 
Back
Top