Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 521
Ehsan Avatar asked Jan 14 '23 04:01

Ehsan


1 Answers

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.

like image 191
MrCode Avatar answered Jan 17 '23 09:01

MrCode