Remove empty fields in an array after foreach in P

2020-03-31 08:30发布

问题:

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 output lists all fields and values regardless of whether they are empty or have been selected. I understand I need to use either unset or array_filter, but cannot figure out how and where I need to insert into code.

if($_POST && count($_POST)) {

    $body = '';

    foreach($_POST as $key=>$value)
        $body .= $key . ": " . $value . "\r\n";

    mail("email@email.com", "Email Received at email@email.com", $body);

回答1:

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


回答2:

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