检查switch语句是否为true

时间:2014-03-03 10:32:14

标签: php switch-statement

我想检查我的switch语句是否为true,如果是,我想用它做一些事情。 e.g。

$a = trim($_POST['code']);

    switch ($a) {
    case "123";
        break;
    case "467";
        break;
    default : "incorrect";
    }

然后我想做一个这样的if语句

if(switch == true) {
    $a = trim($_POST['code']);
}
else {
$Error ="incorrect code";
$hasError = true;
}

if(switch == true)不正确。我如何检查switch语句是否为真?

感谢您的时间。

6 个答案:

答案 0 :(得分:4)

交换机语句 表达式,因此不能为“true”。您只能使用开关语句来产生副作用,例如分配变量。

例如(修复语法错误)

$valid = false; # default to false

switch ($a) {
    case "123":
    case "467":
        $valid = true; # yay, "valid!"
        break;
    default:
        break;
}

if ($valid === true) {
  # ..
}

虽然在实践中,我很少编写看起来像这样的代码 - 只需在交换机中执行操作或直接使用if语句;使用一个函数,可能包含switch-statement来编写更干净的代码。

function isValid($secretCode) {
  switch ($secretCode) {
    case "123":
    case "467":
      return true;
    default:
      return false;
  }
}

if (isValid($a)) {
  # ..
}

答案 1 :(得分:2)

case关键字以 : (冒号)结尾,而不是 ; (分号)

答案 2 :(得分:1)

我会朝完全相反的方向前进,而是使用in_array代替:

//If trim($_POST['code']) is either 123 or 467 then..
if ( in_array( trim( $_POST['code'] ), array("123", "467") ) {
    echo 'Correct!';
} else {
    echo 'Incorrect!';
}

答案 3 :(得分:1)

$a = trim($_POST['code']);
$hasError = 0;

switch ($a) {
    case "123":
    break;

    case "467":
    break;

    default : 
        $hasError = 1;
    break;
}

答案 4 :(得分:0)

$switch_true = true;
switch($a){
    case 123: break; // $switch_true stays true
    case 267: break; // $switch_true stays true
    // for any other value
    default: $switch_true = false; break; // $switch_true becomes false
}
var_dump($switch_true);

有关 switch here 的更多信息。

但你应该使用:

$switch_true = in_array($a, array(123, 267));

Switch并非真正用于此类用途。

答案 5 :(得分:0)

您的代码应该是这样的:

    $a = trim($_POST['code']);

    switch ($a) {
    case "123":
        break;
    case "467":
        break;
    default : "incorrect";
    }

替换:(冒号); (分号)。