PHPNewuser
PHPNewuser

Reputation: 43

PHP array post data

Form: $headerValues=array();

$headerValues[1][2]="Test";
... 
....
echo "<input type=\"hidden\" name=\"ArrayData\" value=\"$headerValues\"/>";
echo "<input type=\"submit\" name=\"submit\" value=\"Submit\" />"; 

How do I read headerValues on FORM POST , I see as ARRAY when I use this code

foreach (array_keys($_POST) as $key) { 
   $$key = $_POST[$key]; 
   print "$key is ${$key}<br />";
   print_r(${$key}); 
} 

Upvotes: 1

Views: 17798

Answers (3)

John Kugelman
John Kugelman

Reputation: 362087

You need to write out multiple <input name="ArrayData[]"> elements, one for each value. The empty square brackets signify to PHP that it should store each of these values in an array when the form is submitted.

$headerValues=array('blah','test');

for ($headerValues as $value) {
    echo "<input type=\"hidden\" name=\"ArrayData[]\" value=\"$value\"/>";
}

Then $_POST['ArrayData'] will be an array you can loop over:

foreach ($_POST['ArrayData'] as $i => $value) {
    echo "ArrayData[$i] is $value<br />";
}

Upvotes: 0

user229044
user229044

Reputation: 239521

The problem is you're outputting the string "ARRAY" as the value of your field. This is what happens when you cast an array to a string in PHP. Check the HTML source next time you have similar problems, it's a pretty crucial step in debugging HTML.

Use this instead:

echo "<input type=\"hidden\" name=\"ArrayData\" value=\"", implode(' ', $headerValues), '"/>';

The way you handle the input is also needlessly complex, this would suffice:

foreach($_POST as $key => $value)
  echo "$key is $value<br />";

Upvotes: 3

Bang Dao
Bang Dao

Reputation: 5112

You can use:

$headerValues=htmlspecialchars(serialize(array('blah','test')));
echo "<input type=\"hidden\" name=\"ArrayData\" value=\"$headerValues\"/>";
echo "<input type=\"submit\" name=\"submit\" value=\"Submit\" />"; 

to get

$value = unserialize($_POST['ArrayData']);

Reference: http://php.net/manual/en/function.serialize.php

Upvotes: 0

Related Questions