有条件地传递参数以起作用

时间:2013-01-24 05:44:44

标签: php logic

我有一个数组:

    <pre>Array
(
    [fname] => adsff
    [lname] => adsf
    [address] => sdfaf
    [city] => sdaf
    [state] => dsfaf
    [zip] => adf
    [phone] => asdf
    [fax] => adsf
    [email] => asdff
    [salary] => asdaf
    [pemp] => asdfaf
    [noofyears] => asdfaf
    [married] => asdfaf
    [children] => asdfaf
    [refname1] => asdfaf
    [refphone1] => adsfaf
    [refname2] => asdfaf
    [refphone2] => sdfaf
    [refname3] => dfsg
    [refphone3] => sdf
    [bank] => sdf
)

我想将这个数组传递给邮件,这样如果任何一个字段为空白,那么就不会在邮件中使用它 例如 : 如果只有fname和lname有值,那么邮件将是

First name = asdff
Last Name= adsf

示例2: 如果只有fname,lname和address有值,那么邮件将是

 First name = asdff
    Last Name= adsf
Address=sdfaf

3 个答案:

答案 0 :(得分:3)

$array = array(); // your array that you posted...
$new_array = array();

foreach ($array as $key => $val) {
    if ( ! empty($val) ) $new_array[$key] = $val;
}

答案 1 :(得分:1)

$mail = '';
foreach ($array as $name => $value) {
   if ($value) {
      $mail .= "$name = $value \n";
   }
}

答案 2 :(得分:1)

我认为使用array_filter

示例

<?php

$entry = array(
             0 => 'foo',
             1 => false,
             2 => -1,
             3 => null,
             4 => ''
          );

print_r(array_filter($entry));
?>

The above example will output:

Array
(
    [0] => foo
    [2] => -1
)

愿这对你有所帮助。