PHP if / else总是转向其他,即使IF成功

时间:2017-10-23 13:54:06

标签: php if-statement

我有这个foreach,它将邮政编码$searchvalue与一系列地区相匹配。如果没有ifelse语句将完成其工作并成功执行。

但是,当我取消注释else时,else始终会被执行。

为什么会这样?

foreach ($districts['district'] as $district) {
    if (in_array($searchvalue, $district['postalcodes'])) { //Search for known Postal Code
        $emails[] = $district['email'];

        //Assign new mail address
        $notification['to'] = implode("",$emails);

        //Continue sending email
        return $notification; //this succeeds without the else below. When the Else is uncommented, this is not executed.
    } 
    else {
        //No known postal code found, fallback
        echo "no valid postal code found, fallback";
        $notification['to'] = $defaultaddress;
        return $notification;
    }
}

1 个答案:

答案 0 :(得分:6)

你的foreach将会逐步浏览多个记录,因此有些记录会匹配,而有些记录则不会。拥有else return的东西将停止执行foreach,因此第一个不匹配的记录将停止循环而不评估所有其余条目。

如果数组中的任何地方匹配,您似乎想要return $notification;,所以将else逻辑移到之外foreach

foreach ($districts['district'] as $district) {
    if (in_array($searchvalue, $district['postalcodes'])) { //Search for known Postal Code
        $emails[] = $district['email'];

        //Assign new mail address
        $notification['to'] = implode("",$emails);

        //Continue sending email
        return $notification; //this succeeds without the else below. When the Else is uncommented, this is not executed.
    }
}

//No known postal code found, fallback
echo "no valid postal code found, fallback";
$notification['to'] = $defaultaddress;
return $notification;

(旁注:您可能想要考虑如果多个记录匹配会发生什么。现在,只有第一个匹配的记录会收到一封电子邮件 - 其余的将被忽略.A {{1根据您的目标和数据,可能不是理想的操作。)