Remove empty fields in an array after foreach in PHP

前端 未结 2 1132
感动是毒
感动是毒 2021-01-16 23:23

I am new to PHP. This is my code from our mailing.php. When a user submits a request, there are 5-7 select-able fields and 20-25 fields that end up not being selected. The o

相关标签:
2条回答
  • 2021-01-16 23:53

    Just before foreach loop you should use this

    $_POST = array_filter($_POST);
    

    Another option is to use a conditional inside foreach loop

    foreach($_POST as $key=>$value)
        if ($value != '' && $value != null)
            $body .= $key . ": " . $value . "\r\n";
    
    0 讨论(0)
  • 2021-01-17 00:01

    You can try this

    if($_POST && count($_POST)) {
         $_POST = array_filter($_POST);
         $body = '';
    
        foreach($_POST as $key=>$value)
            $body .= $key . ": " . $value . "\r\n";
    
        mail("email@email.com", "Email Received at email@email.com", $body);
    

    OR

    if($_POST && count($_POST)) {
         $body = '';
         foreach($_POST as $key=>$value){
            $trim_value = trim($value);
            if (!empty($trim_value)){
                $body .= $key . ": " . $value . "\r\n";
            }
    
         }
    mail("email@email.com", "Email Received at email@email.com", $body);
    
    0 讨论(0)
提交回复
热议问题