如何在php中使用switch

时间:2017-09-17 07:19:20

标签: php switch-statement

if (isset($_POST["submit"])){
$oride='';
$count = "25";
$origin = $_POST["origin"];
$destinataion = $_POST["destination"];
$oride = ($destination = $_POST["destination"] - $origin= $_POST["origin"]);

    switch (true) {
    case ($count<="0"):
    echo "invalid";
        break;

    case ($count==="15"):
    echo $count;
        break;

    case ($count==="16"):
    $total = $count + "1";
    echo $total;
        break;
    default:
        echo "hello";
}  }

代码将计算1st然后执行开关,具体取决于计算结果。我试过了,但是它太长了,因为案子会达到130.

2 个答案:

答案 0 :(得分:1)

您必须在switch语句中使用var $ count,并使用常量

Foo

答案 1 :(得分:0)

你必须为switch语句提供一个表达式,而case语句只是&#34;版本&#34;该表达式的结果。你唯一不能直接做的就是&#34;&lt; = 0&#34;表达,但你可以解决它:

if (isset($_POST["submit"])){
$oride='';
$count = "25";
$origin = $_POST["origin"];
$destinataion = $_POST["destination"];
$oride = ($destination = $_POST["destination"] - $origin= $_POST["origin"]);

// --- normalize $count:
$count = $count <= 0 ? 0 : $count;

// use $count as expression:
    switch ($count) {
    case 0:
    echo "invalid";
        break;

    case "15":
    echo $count;
        break;

    case "16":
    $total = $count + "1";
    echo $total;
        break;
    default:
        echo "hello";
}  }