doupuchen6378 2016-10-04 18:56
浏览 50
已采纳

PHP Conditional Statement跳过elseif

I have an array of checkboxes coded as:

<form action="CascadeFunction.php" method="post" name="cascader" id="cascader">
    <input name="checkbox[]" type="checkbox" value="EMEA" /><label for="EMEA">EMEA</label><br />
    <input name="checkbox[]" type="checkbox" value="NAM" /><label for="NAM">NAM</label><br />
    <input class="btn btn-primary" name="Submit" type="submit" id="submit" value="POST &amp; CASCADE" />
</form>

The following code checks which of those checkboxes are checked. Then by checking the imploded checkbox value, it adds the corresponding email addresses to the $toList array.

$checkbox = $_POST['checkbox'];
$checkboximploded = implode($checkbox);
$toList = array(
    'firstemail@email.com' => 'First Email',
    'secondemail@email.com' => 'Second Email',
);

if(!empty($_POST['checkbox'])) {
    foreach ($checkbox as $value) {

            if (preg_match('/EMEA/',$checkboximploded)) {
                $toList["thirdemail@email.com"] = "Third Email";
                $toList["fourthemail@email.com"] = "Fourth Email";
            }
           elseif (preg_match('/NAM/',$checkboximploded)) {
                $toList["fifthemail@email.com"] = "Fifth Email";
                $toList["sixthemail@email.com"] = "Sixth Email";
        }   
}   
            foreach($toList as $email => $name) {
                $mail->AddAddress($email, $name);
            }

The code works perfectly only if one of the checkboxes is checked. The problem is, if both are checked, it only adds the email addresses found on the 1st if statement and never continues to the elseif statement. What I want to happen is if all 2 checkboxes are checked, it should add all 4 email addresses to the existing $toListarray.

I already spent 8 hours solving the issue but can't find the correct solution. Kindly advise why it seems to be skipping the elseif statement.

  • 写回答

3条回答 默认 最新

  • dounao1856 2016-10-04 19:03
    关注

    Either:

    • Change your elseif to an if (and get rid of the loop), or
    • Change your preg_match to check against $value

    Here's why. If both check boxes are ticked, then $_POST['checkbox'] is array ('EMEA', 'NAM') and thus $checkboximploded is "EMEANAM", which matches the regular expression of the if as well as the elseif. But since if comes first, if wins, regardless of the fact that you're iterating over $checkbox.

    Also, preg_match may be overkill: strpos would suffice in this case.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题