views:

46

answers:

3

I"m having trouble receiving a list of items that are checked in a field of checkboxes which are part of a form.

I have an HTML table with a few checkboxes:

HTML

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

PHP - this is what I'm using to post the form to an email address

foreach($_POST as $key => $val) {

$body .= $key . " : " . $val . "\r\n";

I get the value in my email as: "carry: Array" -- not the actual values that are selected. How do I handle an array of checkboxes selected in a form and post it?

Ideally, I would want: "carry: 1; 2; 3" (without the quotes)

+1  A: 

It's printing carry: Array because that's exactly what it is. You need to loop over it (another loop inside the first) to access the values inside:

foreach($_POST as $key => $val) {
    if($key == 'carry') {
        foreach($val as $carry) {
            $body .= $carry;
        }
    }
    else {
        $body .= $key . " : " . $val . "\r\n";
    }
}

That's completely untested but hopefully the logic is sound :)

Matt
or if he's looking for 'carry': `foreach( $_POST['carry'] as $key => $val );`
Dan Heberden
+2  A: 

If you want the string '1; 2; 3', you should join together the items in the array:

$carry= implode('; ', $_POST['carry']);

However doing so will naturally cause ambiguous results if any of the items in the array themselves have a semicolon in.

To iterate over the post array allowing any of its members to be arrays:

foreach($_POST as $key=>$val) {
    if (is_array($val))
        $val= implode('; ', $val);
    $body.= "$key: $val\r\n";
}

Or, if you don't need so much control over the exact formatting and a debugging dump is fine (but you need to see more than just the useless string 'Array':

$body= var_export($_POST, TRUE);
bobince
+1  A: 

You can check if the value is an array and handle it differently:

foreach($_POST as $key => $val) {
  if (is_array($val)) {
    $body .=  $key . " : " . implode(",",$val) . "\r\n";
  } else {
   $body .= $key . " : " . $val . "\r\n";
  }
}
Craig
Thanks, this worked like a charm. Wasn't familiar with the is_array() or implode().
John H.