将项目推送到PHP数组的末尾?

时间:2015-05-29 00:50:55

标签: php arrays append

我有以下代码......

if ($email_selection == "primary") {

     $default_select = "<option value=''>Select Email</option>";
     $select_1 = "selected";
     $to_array[] = $profile_primary_email;

} elseif ($email_selection == "secondary") {

     $default_select = "<option value=''>Select Email</option>";
     $select_2 = "selected";
     $to_array[] = $profile_primary_email;

} elseif ($email_selection == "both") {

     $default_select = "<option value=''>Select Email</option>";
     $select_3 = "selected";
     $to_array[] = $profile_primary_email . ',' . $profile_secondary_email;

} 

if ($manual_email != "") {

    $to_array[] = $manual_email;

}

$to_array_count = count($to_array);

$to = $to_array["0"];

for ($v = 1; $v < $to_count; $v++) {

    $to = $to . ',' . $to_array[$v];

}

此代码的功能是获取选择输入的值,并根据选择输入的值将电子邮件地址推送到$to_array的末尾。然后,该脚本会使用逗号分隔每个电子邮件的字符串,该逗号稍后将用作PHP $to函数中的mail()

由于某种原因,select字段包含任何值,$manual_email中包含的电子邮件地址不会附加到数组中。但是,如果select字段没有值,则$manual_email通常会附加到空数组。

1 个答案:

答案 0 :(得分:1)

我不打算重写所有代码,但是:

$to_array_count = count($to_array);

$to = $to_array["0"];

for ($v = 1; $v < $to_count; $v++) {

   $to = $to . ',' . $to_array[$v];

}

应该只是:

$to = implode(',', $to_array);

不确定为什么你不会使用foreach循环,如果你打算以疯狂的方式去做。