Evan H. Evan H. - 4 months ago 12x
PHP Question

Get values of all POST checkboxes in array via PHP?

I'm making a form that allows the user to check where they want certain push notifications to go. There is multiple checkboxes that get POSTed in PHP. Here is my PHP snippet:

if(isset($_POST['Submit'])) {
function sendMessage(){
$pushmessage = ($_POST['PushMessage']);
$content = array(
"en" => $pushmessage

foreach($_POST['formDeliver'] as $check) {
$segments = $check;

$fields = array(
'app_id' => "app-id-here",
'included_segments' => array($segments),
'data' => array("foo" => "bar"),
'contents' => $content

Edit: Here is my checkbox code:

<input class="LCB" type="checkbox" id="district" value="All" name="formDeliver[]" checked><label class="light" for="district">District-Wide (Everyone)</label><br>
<input class="LCB" type="checkbox" id="high" value="High School" name="formDeliver[]"><label class="light" for="high">High School</label><br>
<input class="LCB" type="checkbox" id="middle" value="Middle School" name="formDeliver[]"><label class="light" for="middle">Middle School</label><br>
<input class="LCB" type="checkbox" id="williams" value="Williams Ave." name="formDeliver[]"><label class="light" for="williams">Williams Ave.</label><br>
<input class="LCB" type="checkbox" id="norwoodv" value="Norwood View" name="formDeliver[]"><label class="light" for="norwoodv">Norwood View</label><br>
<input class="LCB" type="checkbox" id="sharpsburg" value="Sharpsburg Elementary" name="formDeliver[]"><label class="light" for="sharpsburg">Sharpsburg Ave.</label><br>
<input class="LCB" type="checkbox" id="athletics" value="Athletics" name="formDeliver[]"><label class="light" for="athletics">Athletics</label>

Whenever the form is submitted, the $fields array submits the message info. I need to pass the segments (values of the checkboxes) as a string like this: "String 1", "String 2", "String 3". Whenever i do this, however, it only grabs the last ticked checkbox and submits it into the $segments variable. Is this something I'm doing wrong or not seeing?


Based on comments, just add the array like so:

'included_segments' => $_POST['formDeliver'],

For a comma sperated list:

Forget the foreach() you are overwriting the $segments variable each time through. Just implode() the checkbox array:

'included_segments' => implode(', ', $_POST['formDeliver']),

In your current code, this would work but is redundant and not needed:

foreach($_POST['formDeliver'] as $check) {
    $segments[] = $check; 
$segments = implode(', ', $segments);