This is my array
$array = array('foo' => 'bar', 'baz', 'bat' => 2);
<form method='POST' action='test.php' onsubmit='return validateForm()' >
echo '<input type="hidden" name="array" value= "'.implode(',', $array).'">';
echo "<<input type='submit' name='Submit' value='submit' />";
echo '</form>';
$arry = explode(',', $_POST['array']);
I am getting key as 0,1,2
. Which should be "foo", "baz", "bat".
How can I get correct key?
If I am wright, you need the array keys after the posting the form with imploding the array values.
I think, json_encode
is a good solution. I am adding another solution.
Add another hidden element which will post array keys with array values.
echo '<input type="hidden" name="values" value= "'.implode(',', array_values($array)).'">';
echo '<input type="hidden" name="keys" value= "'.implode(',', array_keys($array)).'">';
In your test.php
$arrayValues = explode(',', $_POST['values']);
$arrayKeys = explode(',', $_POST['keys']);
$yourFinalArray = array_combine($arrayKeys, $arrayValues);
Encode your array and decode using, for example, json_encode
and json_decode
functions.
Function implode
is ignoring the array keys.
Actually there is something wrong. Yuo are exploding an array while you should implode it. Also you cannot retrieve baz
as key since it is a value. It's key is actually 0, have a look at this sample
$array = array('foo' => 'bar', 'baz', 'bat' => 2);
$arry = implode(',', $array_key($array));
echo $arra;
This will transform you array's key in a comma separated value list
foo,0,bat
In the other way if you will get values from your post array you will get
$array = array('foo' => 'bar', 'baz', 'bat' => 2);
$arry = implode(',', $array_values($array));
echo $arra;
Output
bar,baz,2
//^ as you can see baz it's between values
don't use ’
, use '
or "
, in your array i see that it will be look like this -> array(3) { ["foo"]=> string(3) "bar" [0]=> string(3) "baz" ["bat"]=> int(2) }
You can send an array in form submit as
page1.php
$array = array('foo' => 'bar', 'baz', 'bat' => 2);
echo "<form method='POST' action='page2.php' onsubmit='return validateForm()' >";
foreach($array as $key=>$value) {
echo '<input type="hidden" name="array[]" value = "'.$key."|".$value.'">';
}
echo "<input type='submit' name='Submit' value='submit' />";
echo '</form>';
?>
page2.php
<?php
$array = array();
foreach($_POST['array'] as $value) {
$a = explode("|",$value);
$array[$a[0]] = $a[1];
}
print_r($array);
?>
Output:
Array
(
[foo] => bar
[0] => baz
[bat] => 2
)