倒置开关案例陈述(直到真)

时间:2014-05-15 08:39:15

标签: php algorithm switch-statement

我正在努力实现一个结果,我只能想到反向开关情况,直到真实陈述。请参阅下面的常规案例陈述:

 $i="bar";
   switch ($i) {
    case "apple":
        echo "i is apple.";
        break;
    case "bar":
        echo "i is bar.";
        break;
    case "cake":
        echo "i is cake.";
        break;
    }

我想要的结果如下:

例如:如果$i = 'apple'我希望它打印i is apple.

例如:如果$i = 'bar'我希望它打印i is apple.i is bar.

例如:如果$i = 'cake'我希望它打印i is apple.i is bar.i is cake

一旦能够实现结果,答案可能不一定使用上述结构

4 个答案:

答案 0 :(得分:1)

试试这个:

<?php
$i = 'bar';

$cases = array(
    'apple' => 'i is apple.',
    'bar' => 'i is bar.',
    'cake' => 'i is cake.',
);

$resp = '';
foreach($cases as $k => $v)
{
    $resp .= $v;
    if($k == $i) break;
}

echo $resp;
?>

Codepad example

答案 1 :(得分:0)

这个带有fallthrough的switch语句与我能想到的OP最相似:

$i = "cake";
$output = "";

switch ($i) {
    case "cake":
        $output = "i is cake." . $output;
    case "bar":
        $output = "i is bar." . $output;
    case "apple":
        $output = "i is apple." . $output;
    default:
        echo $output;
        break;
}

答案 2 :(得分:-1)

您可以使用常规IF语句,但请在回显后进行检查。

<?php
function checkMe($i) {
  echo "i is apple.";
  if ($i=="apple")
    return;

  echo "i is bar.";
  if ($i=="bar")
    return;

  echo "i is cake.";
  if ($i=="cake")
    return;
}

checkMe("bar");
?>

Codepad example

答案 3 :(得分:-1)

开关会变成这样:

$i="bar";

switch ($i)
{
    case "apple":
    case "bar":
    case "cake":

      echo "i is apple.";
      if ($i == "apple") break;

      echo "i is bar.";
      if ($i == "bar") break;

      echo "i is cake.";
      if ($i == "cake") break;

      default:
}