如何在我的交换机案例中避免冗余的“else”(if / else)

时间:2016-03-26 20:24:22

标签: php

如果我要删除if / else函数中的“else”,$ on_sale变量由于某种原因会变为“true”,即使if语句返回false也是如此。

$mm = date('n');
$on_sale = false;
foreach ($services as $service) {

    switch ($service) {
        case 'Example Service':
            if ($mm == 3 || $mm == 4) { #pretend this returns false
                $service = '1% Off ' .$service;
                $on_sale = true;
            } else {
                $on_sale = false; #<---- why must I do this?
            }
            break;
        default:
            $service;
            $on_sale = false;
            break;
    }

    #more code...
}

我期望的工作:

$mm = date('n');
$on_sale = false;
foreach ($services as $service) {

    switch ($service) {
        case 'Example Service':
            if ($mm == 3 || $mm == 4) { #pretend this returns false
                $service = '1% Off ' .$service;
                $on_sale = true;
            }
            break;
        default:
            $service;
            $on_sale = false;
            break;
    }

    #more code...
}

编辑:

我错误地在foreach循环之外声明了我的$ on_sale变量,因此对于每次迭代,$ on_sale变量都不是“重置”。

为:

$mm = date('n');
$on_sale = false;
foreach ($services as $service) {
   ...

好:

$mm = date('n');
foreach ($services as $service) {
    $on_sale = false;
    ...

1 个答案:

答案 0 :(得分:0)

(这可能不是一个好的答案,但你可能会了解一些关于开关的事情。)

我不确定Private Function SourceForgeGetDirectUri(Uri As String) As String Dim doc As HtmlDocument = New HtmlWeb().Load(Uri) 'loads the website Dim aHref As HtmlNode = doc.DocumentNode.SelectSingleNode("//a[@class='direct-download']") 'finds the a href of the direct download Dim DirectLink = aHref.GetAttributeValue("href", "") ' gets the link Return DirectLink End Function 案例中的$service;应该做什么,但是:

你通过(重新)移动default语句使一个案例流入下一个案例:

break

对于switch (x) { case a: do A // don't break case b: do B break; } ,这将ado A,因为do B不会停止。对于case a,这只会b

在你的情况下:

do B