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

3 Answers 3

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]
}
Sign up to request clarification or add additional context in comments.

5 Comments

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.
Is your form using method='get'? Then use $_GET instead of $_POST.
Or use $_REQUEST, which works with either; I've edited my code.
I'm using the post method and it works fine for 'shortcut' but for 'ses' it says that it's empty
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.
1

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
}

2 Comments

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.