Page 1 of 1

POSTing complete arrays

Posted: Fri Apr 01, 2005 7:49 am
by bredoteau
I tried writing a function for putting a complete array into hidden fields, but failed:

Code: Select all

function insertarray ($array, $arrayname) 
{ 
$include=&quote;&quote;; 
foreach ($array as $key => $value) { 
$include = $include.&quote;<input type=hidden name ='$&quote;.&quote;$arrayname&quote;.&quote;ї$key]' value='$value'><br />\n&quote;; 
} 
return $include;

Code: Select all

echo insertarray($arrayname, &quote;arrayname&quote;);
I thought if this would be submitted and extracted, the complete array would be regenerated, but it is not created.
I also do not know how foreach behaves on arrays that are more than 2-dimensional...!?

How can I drag arrays confortably to the next site? (the contents of the array is dynamic, i.e. both values and keys might change)


Greetings,


feyd | Please review how to post code using

Code: Select all

and

Code: Select all

tags. Read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url][/color]

Posted: Fri Apr 01, 2005 1:09 pm
by feyd
  1. remove the $ you added to the name.
  2. the $value variable will be a copy (if I remember correctly) of the element involved. So if it's an array, you need to make it stored into a string in some fashion.
  3. if you transmit "sensitive" information in this, it's very very easily manipulated. I'd highly recommend using sessions.

wao, cool reply!

Posted: Sat Apr 02, 2005 3:45 am
by bredoteau
Cool, thanks for the kind and fast help!

I have updated the function to this and it works fine:
(anyone interested may of course reuse it)

Code: Select all

<?php
function insertarray ($array, $arrayname) //DOES NOT ADD INDEX
{
$include=&quote;&quote;;
foreach ($array as $key => $value) {
	if (is_array($value)) 
		{$include .= insertarray($arrayї$key],&quote;$arrayname&quote;.&quote;ї$key]&quote;);}
	else
		{	
	$include .=&quote;<input type=hidden name ='&quote;.&quote;$arrayname&quote;.&quote;ї$key]' value='$value'>&quote;;
		}
}
return $include;
}?>


The only flaw left is that it does not create the index numbering (using a number instead of a key). Is there any way to copy it?

About security: sure I will use sessions of some kind. :)

Posted: Sat Apr 02, 2005 7:34 am
by feyd
if $array is a numeric array, it will output the key's numerically.

Posted: Sat Apr 02, 2005 2:11 pm
by bredoteau
The original array has both keys and indexes, i.e.
$array["key0"] = $array[0]; The foreach used only outputs the keys it seems. Sure I can count the keys and add the indexing manually, but maybe there is a more professional way. What is a numeric array?

Posted: Sat Apr 02, 2005 2:39 pm
by feyd

Code: Select all

$ex = array(10, 12, 42, 'hi', 'cheese', 'foo');
foreach($ex as $k => $v)
{
  echo $k . ' => ' . $v . &quote;\n&quote;;
}

Code: Select all

0 => 10
1 => 12
2 => 42
3 => hi
4 => cheese
5 => foo