Ehsan
Ehsan

Reputation: 2285

How can I use several form inputs with the same name?

I have several checkbox (I don't know number of them) that create from a loop in a form.

<form>
<input type="checkbox" name="id" value="id">
<input type="checkbox" name="id" value="id">
...//create in a loop
<input type="checkbox" name="id" value="id">
</form>

My question is that How can I read them, If I use <?php $_REQUEST['id']; ?>, it only reads the last checkbox.

Upvotes: 4

Views: 293

Answers (2)

MrCode
MrCode

Reputation: 64536

Use an input array:

<input type="checkbox" name="id[]" value="id_a">
<input type="checkbox" name="id[]" value="id_b">
<input type="checkbox" name="id[]" value="id_c">
<!--                           ^^ this makes it an array -->

$_REQUEST['id'] can be accessed:

foreach($_REQUEST['id'] as $id)
{
    echo $id;
}

Outputs

id_a
id_b
id_c

Side note: this works with $_POST and $_GET (not just $_REQUEST). Generally speaking though $_REQUEST should be avoided if possible.

Upvotes: 13

emallove
emallove

Reputation: 1567

Use unique id's for your checkboxes, e.g.,

<form>
<input type="checkbox" name="id1" value="value1">
<input type="checkbox" name="id2" value="value2">
...//create in a loop
<input type="checkbox" name="id3" value="value3">
</form>

Upvotes: -4

Related Questions