Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using PHP checkbox array with GET Method

Can I use PHP checkbox array with the GET Method? And if there are two checkboxes clicked, will that result in: some.php?param=1&param=2 ?

As you know, I am not used to write into database, I'm just getting the parameters. Thanks.

like image 322
Anggie Aziz Avatar asked Aug 09 '26 19:08

Anggie Aziz


2 Answers

You need to pass the checkboxes with the same field name followed by [] so PHP recognizes the array.

Like so:

<input type="checkbox" name="foo[]" value="bar1">
<input type="checkbox" name="foo[]" value="bar2">
<input type="checkbox" name="foo[]" value="bar3">

So the GET would be:

phpfile.php?foo[]=bar1&foo[]=bar2&foo[]=bar3

if every checkbox is clicked. (POST similar)

Please note, that only the clicked checkboxes will be submitted. So, if just bar1 and bar2 are clicked, then the GET would be

phpfile.php?foo[]=bar1&foo[]=bar2

Then you can access that array via

$_GET["foo"]

or similar to POST

$_POST["foo"]

Hope that helps :-)

like image 130
Stefan Avatar answered Aug 12 '26 11:08

Stefan


In addition to what steve said, you could also add certain keys if you'd like to:

<input type="checkbox" name="foo[my_id_1]" value="bar1">
<input type="checkbox" name="foo[my_id_2]" value="bar2">
<input type="checkbox" name="foo[my_id_3]" value="bar3">
like image 33
LeEnno Avatar answered Aug 12 '26 12:08

LeEnno



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!