0

I would like to pass an array from a form by changing its values (inputs). the user can change the values ​​of the inputs, how could retrieve the array changed?

for example...

  <?php $vector = array("product1" => 150, "product2" => 120); ?>
  <table>
  <form action="page2.php" method="get">

  <?php foreach ($vector as $key => $value) { 
 echo "<tr><td>Product: $name</td><td><input type='text' name='$key' 
     value='$value'/>  
     </td>";
  }
  <tr>
<td><input type="submit" name="process" value="Submit" /></td>
  </tr>
  </form>
  </table>
  ?>

  // on the other page...page2.php

  if (isset($_GET['process'])){ 
 $foo = $_GET[$vector]; // the array i want
 echo var_dump($foo);
  }

3 Answers 3

2

HTTP, by design, allows arrays through POST/GET. Simply have the related items with the same name and ending with two opposing square brackets, like so:

<input type="text" name="data[]" value"First"/>
<input type="text" name="data[]" value"Second"/>

And on the server...

print_r($_REQUEST['data']);

Prints...

Array
(
    [0] => First
    [1] => Second
)

Pretty convenient, hmm?

1

Parameters are passed as an array form. So you have to parse the requested variables

Here is the revised version of your code.

<?php $vector = array("product1" => 150, "product2" => 120); ?>
  <table>
  <form action="page2.php" method="get">

  <?php foreach ($vector as $key => $value) { 
 echo "<tr><td>Product: $name</td><td><input type='text' name='$key' 
     value='$value'/>  
     </td>";
  }
  <tr>
<td><input type="submit" name="process" value="Submit" /></td>
  </tr>
  </form>
  </table>
  ?>

  // on the other page...page2.php

  if (isset($_GET['process'])){ 
    unset($_GET['process']);
    $foo = $_GET ;
    echo var_dump($foo);
 }
3
  • You don't have to parse the parameters and you specially would not want to depend on all possible parameters that could have ended up in $_GET.
    – Christian
    Mar 1, 2012 at 23:31
  • Christian I also know this but he want the exact same array to e send so that array he is getting directly through $_GET method thats why I simply emphasis on the $_GET method Mar 1, 2012 at 23:45
  • Just because it works doesn't mean it's well written. There are many smarter ways to avoid this issue, such as by prefixing the array indices. Relying blindly on the contents in $_GET is a serious issue.
    – Christian
    Mar 1, 2012 at 23:49
1

Try to just make it

$foo = $_GET ;

If you don't want the 'process' to be in the array, first call

unset($_GET['process']);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.