I am using php mail() for my contact form. I have a checkbox input with multiple choices. But when a form is submitted, the value in email is 'Array'. Below is the php and html.
Can anyone suggest what's wrong?
HTML
<div class="col-lg-5">
<div class="form-group">
<div style="margin-bottom:-25px;"><label for="form_covers">Additional Covers</label><br />
<input type="checkbox" id="supertopup" name="addcover[]" value="Super Topup"><label for="supertopup"><span style="margin-left:5px;">Super Topup</span>
<input type="checkbox" id="criticalillness" name="addcover[]" value="Critical Illness"><label for="criticalillness"><span style="margin-left:5px;">Critical Illness</span>
<input type="checkbox" id="cancercare" name="addcover[]" value="Cancer Care"><label for="cancercare"><span style="margin-left:5px;">Cancer Care</span>
<input type="checkbox" id="heartcare" name="addcover[]" value="Heart Care"><label for="heartcare"><span style="margin-left:5px;">Heart Care</span></div>
<div class="help-block with-errors"></div>
</div>
</div>
PHP
$fields = array('name' => 'Name', 'phone' => 'Phone', 'email' => 'Email', 'hpolicytype' => 'Policy Type', 'addcover' => 'Additional Covers', 'port' => 'Port Existing Policy', 'member1' => '1st Member Name', 'dob1' => '1st Member Date of Birth', 'member2' => '2nd Member Name', 'dob2' => '2nd Member Date of Birth', 'member3' => '3rd Member Name', 'dob3' => '3rd Member Date of Birth', 'member4' => '4th Member Name', 'dob4' => '4th Member Date of Birth');
$emailText = "You have a new message from your contact form\n=============================\n";
foreach ($_POST as $key => $value) {
// If the field exists in the $fields array, include it in the email
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
Email Snapshot
There is one more problem in email that is sent. The date format is incorrect. In the html form the date format is dd-mm-Y whereas the email received has date format Y-mm-dd.
How to change the date format in email?
Thanks & Regards,
Pratik
My Answer:
To handle multiple checkboxes in PHP, you can use an array in the name attribute of the checkboxes. This way, when the form is submitted, you can access the values of the checked checkboxes as an array in PHP.
Here's an example of how you can do this:
HTML form:
html
PHP code in process.php:
php
if(isset($_POST['colors'])){
$selectedColors = $_POST['colors'];
foreach($selectedColors as $color){
echo $color . "
";
}
}
In this example, the checkboxes for colors have the name attribute set as "colors[]", which creates an array of values in PHP. When the form is submitted, you can access the selected colors as an array in the $_POST superglobal variable. You can then loop through the array to display or process the selected values.
Rate this post
3 of 5 based on 3875 votesComments