1

This is the HTML:

<input type="text" name="shortcut[]" value="a"/> do <input type="text" name="ses[]" value="1" disabled/><br>
<input type="text" name="shortcut[]" value="b"/> do <input type="text" name="ses[]" value="2" disabled/><br>
<input type="text" name="shortcut[]" value="c"/> do <input type="text" name="ses[]" value="3" disabled/><br>

How do I pass the values to PHP but connect the indexes of both arrays?

i.e.
put in database value 1 where something = a,
put in database value 2 where something = b
and so on ...

Martin
  • 710
  • 2
  • 11
  • 18

3 Answers3

1

The indexes are connected automatically, since they're numeric arrays.

$nvals = count($_REQUEST['shortcut']);
for ($i = 0; $i < $nvals; $i++) {
  // do something with $_REQUEST['shortcut'][$i] and $_REQUEST['ses'][$i]
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • I've tried something similar to this but it seems that $_POST['ses'] is not an array, and i'm not sure why. I also tried merging the arrays without any success. – Martin Dec 14 '12 at 20:24
  • Is your form using `method='get'`? Then use `$_GET` instead of `$_POST`. – Barmar Dec 14 '12 at 20:27
  • Or use `$_REQUEST`, which works with either; I've edited my code. – Barmar Dec 14 '12 at 20:28
  • I'm using the post method and it works fine for 'shortcut' but for 'ses' it says that it's empty – Martin Dec 14 '12 at 20:30
  • It's because you've disabled those elements. Disabled form fields aren't submitted. Use `readonly` instead, if you want to prevent the user from editing it. – Barmar Dec 14 '12 at 20:33
0

Combined array: array_map(null,$_POST['shortcut'],$_POST['ses']);

But you could of course could foreach over one of the 2, and fetch the other by key.

Note that if you have elements which may or may not be sent (checkboxes for instance), the only way to keep groups together is to assign them a number beforehand (name=sess[1], name=sess[2], etc.)

Wrikken
  • 69,272
  • 8
  • 97
  • 136
0

You can specify shortcut value as the key and the ses value as the value attribute:

<input type="text" name="input[a]" value="1" />
<input type="text" name="input[b]" value="2" />
<input type="text" name="input[c]" value="3" />

On the server-side you could use a foreach loop to iterate over the array:

foreach ($_POST['input'] as $shortcut => $ses) {
    // process $shortcut and $ses
}
kulishch
  • 158
  • 1
  • 1
  • 6
  • yes, but i'm not sure how to make the user enter 2 values in the inputs (the ones that need to be connected) – Martin Dec 14 '12 at 20:22
  • 1
    @martin with the `disabled` attribute, the user will never be able to enter a value plus it won't be submitted with the rest of the form (see [Successful Controls](http://www.w3.org/TR/html401/interact/forms.html#h-17.13.2)). You might want to consider using a `hidden` control (`type="hidden"`) instead of `text` control (`type="text"`). The user won't see it but it will be submitted with the rest of the form. – kulishch Dec 14 '12 at 20:42