Search code examples
phpforeachphpmailer

Cant send empty checkbox value in phpmailer


I'm working in a e-mail form using phpmailer, there is a problem every-time checkboxes are kept empty, so I figure out the problem is in the expression bellow:

$f_select = '';
foreach ($_POST['select'] as $key => $value) {
    $f_select .= $value."\r\n";
}

It is returning the following error:

Warning: Invalid argument supplied for foreach() in /home/alive-web-tech/www/nagoyashobotenken/contact/complete.php on line 23

How can I fix this problem? I guess I need to create a condition telling that when the checkbox value is empty something must happen to prevent the error.


Solution

  • There are 2 ways to solve this problem.

    1. If you really need the values of the checkboxes even if they were not checked then you must update your form to include an hidden input with value 0 for each checkbox you have:

      <input type="hidden" name="select[firstCheckbox]" value="0" />
      <input type="checkbox" name="select[firstCheckbox]" />
      
    2. If you don't care about the empty values of the checkbox then you can simply verify if the posted data is empty before entering the loop:

      $f_select = '';
      if (!empty($_POST['select'])) {
          foreach ($_POST['select'] as $key => $value) {
              $f_select .= $value."\r\n";
          }
      }