-6

Is it possible to get an output like this using only 1 input?

<input name="value"/>
$_POST['value'] = 1;
$_POST['value'] = 2;
$_POST['value'] = 3;
$_POST['value'] = etc;

EDIT: I'm trying to pass an array using a single form input.

Mat
  • 25
  • 1
  • 4

3 Answers3

1

To submit multiple input with same name, append brackets [] at the end like this

<input type="text" name="bob[]" />
<input type="text" name="bob[]" />
<input type="text" name="bob[]" />
<input type="text" name="bob[]" />
<input type="text" name="bob[]" />

On the other side, bob will be an array :

<?php

$Bob = (isset($_POST['bob']) === TRUE ? $_POST['bob'] array());

echo 'RES:'. implode(',', $Bob);

?>
David Bélanger
  • 7,400
  • 4
  • 37
  • 55
0

No, not unless you store the values one at a time, using ajax perhaps.

Teena Thomas
  • 5,139
  • 1
  • 13
  • 17
0

Your question is a little unclear, but if you're trying to pass an array using a single form input the short answer is no, using a single element you cannot pass an array into the POST array (with the exception of the multi-select form element), but it's easy with a tiny bit of processing once you submit. You just use a delimiter on the value and explode it in PHP:

In HTML:

<input name="value" value="1|2|4|4|5" />

In PHP

$values = explode('|',$_POST['value']);

This will result in:

$values[0] == 1;
$values[1] == 2;
...

However, there is never a way to get a PHP array to have multiple values for a single key at the same time, so you can never have a PHP array that looks like:

$_POST['value'] = 1;
$_POST['value'] = 2;
$_POST['value'] = 3;
$_POST['value'] = etc;

Because for any array (_POST or otherwise) $array[KEY] can not have two values (i.e. how can if ($_POST['value'] === $_POST['value']) ever not be true? It can't, any more that if ($x===$x) or if (1===1) can be false). You can, however, use a multi-dimensional array, which would look like:

$_POST['value'][0] = 1;
$_POST['value'][1] = 2;
$_POST['value'][2] = 3;
$_POST['value'][3] = 'etc';

and then work with it by:

foreach($_POST['value'] as $key =>$value){
    echo $value.',';
}

which would output

1,2,3,etc
Community
  • 1
  • 1
Ben D
  • 14,321
  • 3
  • 45
  • 59
  • you should add info about array notation in html field names. :) – Tim G Sep 19 '12 at 21:19
  • i *think* that the OP was interested in a single input -> multiple outputs rather than just how to pass an array into the _POST array. Though the question isn't exactly clear – Ben D Sep 19 '12 at 21:25