在PHP中使用foreach之后,删除数组中的空字段 [英] Remove empty fields in an array after foreach in PHP
本文介绍了在PHP中使用foreach之后,删除数组中的空字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是PHP新手。这是我的mailing.php中的代码。当用户提交一个请求时,有5-7个可选字段和20-25个字段,最终没有被选中。输出列出所有字段和值,不管它们是空的还是已经被选择的。我知道我需要使用 unset
或 array_filter
,但是不知道如何以及在哪里需要插入代码<$ p
$ b
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);
推荐答案
b
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);
这篇关于在PHP中使用foreach之后,删除数组中的空字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文