Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

foreach checkbox POST in php

Tags:

post

checkbox

php

Basically my question is the following, how can i select on "Checked" checkbox's while doing a $_POST request in PHP, currently i have the checkbox's doing an array as shown below.

<input type="checkbox" value="1" name="checkbox[]">
<input type="checkbox" value="2" name="checkbox[]">
<input type="checkbox" value="2" name="checkbox[]">
<input type="checkbox" value="3" name="checkbox[]">

I want to be able to do something like this

foreach(CHECKED CHECKBOX as CHECKBOX) {
   echo CHECKBOX VALUE;
}

I've tried doing similar to that and it's not echoing anything.

like image 324
Curtis Crewe Avatar asked Dec 04 '22 12:12

Curtis Crewe


1 Answers

foreach($_POST['checkbox'] as $value) {

}

Note that $_POST['checkbox'] will only exist if at least one checkbox is checked. So you must add an isset($_POST['checkbox']) check before that loop. The easiest way would be like this:

$checkboxes = isset($_POST['checkbox']) ? $_POST['checkbox'] : array();
foreach($checkboxes as $value) {
    // here you can use $value
}
like image 51
ThiefMaster Avatar answered Dec 09 '22 16:12

ThiefMaster