Martin
Martin

Reputation: 711

Passing arrays from HTML form to PHP

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 ...

Upvotes: 1

Views: 9257

Answers (3)

Barmar
Barmar

Reputation: 782407

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]
}

Upvotes: 1

kulishch
kulishch

Reputation: 178

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
}

Upvotes: 1

Wrikken
Wrikken

Reputation: 70540

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.)

Upvotes: 0

Related Questions