سؤال

I am trying to achieve a result which I can only think of in terms of a reverse switch case until true statement. See regular case statement below:

 $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;
    }

The result I want is as follows:

Eg: if $i = 'apple' I want it to print i is apple.

Eg: if $i = 'bar' I want it to print i is apple.i is bar.

Eg: if $i = 'cake' I want it to print i is apple.i is bar.i is cake

The answer may not necessarily use the structure above once it can achieve the result

هل كانت مفيدة؟

المحلول

Try this:

<?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

نصائح أخرى

This switch statement with fallthroughs is the most similar to the OP's that I can think of:

$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;
}

You could just use a regular IF statement, but put the check AFTER the echo.

<?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

The switch would become like this:

$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:
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top