开发者

PHP post checkboxes help

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($_POS开发者_C百科T 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)


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";
  }
}


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);


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 :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜