我有这个foreach
,它将邮政编码$searchvalue
与一系列地区相匹配。如果没有if
,else
语句将完成其工作并成功执行。
但是,当我取消注释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;
}
}
答案 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根据您的目标和数据,可能不是理想的操作。)