PHP 中的条件 switch 语句

发布于 2024-12-10 17:27:09 字数 424 浏览 1 评论 0原文

我已经习惯了 vb.net 的 Select Case 语法本质上是一个 switch 语句,您可以在其中执行诸如 Case Is > 之类的操作5 如果匹配,它将执行该案例。

由于我不知道 PHP 中的实际名称,我该如何做我将称之为“条件 switch 语句”的事情呢?

或者,有什么快速的方法来管理这个问题?

switch($test)
{
    case < 0.1:
        // do stuff
        break;
}

这就是我目前尝试过的。

I'm quite used to vb.net's Select Case syntax which is essentially a switch statement, where you can do things like Case Is > 5 and if it matches, it will execute that case.

How can I do what I'm going to call "conditional switch statements" since I don't know the actual name, in PHP?

Or, what's a quick way to manage this?

switch($test)
{
    case < 0.1:
        // do stuff
        break;
}

That's what I've tried currently.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

我认为您正在寻找类似的东西(这不完全是您想要的,或者至少我理解是您的需要)。

switch (true) 查找计算结果为真值的情况,并执行其中的代码,直到第一次中断;它遇到。

<?php

switch (true) {

case ($totaltime <= 1):
echo "That was fast!";
break;

case ($totaltime <= 5):
echo "Not fast!";
break;

case ($totaltime <= 10):
echo "That's slooooow";
break;
}

?>

I think you're searching for something like this (this is not exactly what you want or at least what I understand is your need).

switch (true) finds the cases which evaluate to a truthy value, and execute the code within until the first break; it encounters.

<?php

switch (true) {

case ($totaltime <= 1):
echo "That was fast!";
break;

case ($totaltime <= 5):
echo "Not fast!";
break;

case ($totaltime <= 10):
echo "That's slooooow";
break;
}

?>
木有鱼丸 2024-12-17 17:27:09

我试图将其添加为 BoltCock 答案的评论,但 SO 告诉我他的答案已锁定,因此我将其作为一个单独的(本质上是多余的)答案:

BoltCock 的“switch(true)”答案是很像以下示例,虽然逻辑上等同于 if + else if + else 可以说更漂亮,因为条件表达式是垂直对齐的,并且是 PHP 中的标准/可接受的做法。

但是 if + else if + else 语法本质上是跨脚本语言通用的,因此任何人都可以立即读取(并且可维护),这也让我点头。

I tried to add this as a comment to the answer by BoltCock, but SO is telling me that his answer is locked so I'll make this a separate (and essentially redundant) answer:

The "switch(true)" answer from BoltCock is much like the following example, which although logically equivalent to if + else if + else is arguably more beautiful because the conditional expressions are vertically aligned, and is standard/accepted practice in PHP.

But the if + else if + else syntax is essentially universal across scripting languages and therefore immediately readable (and maintainable) by anyone, which gives it my nod as well.

桃气十足 2024-12-17 17:27:09

在 PHP 8.0+ 中,还有另一种方法可以实现此目的,即使用

如果每种情况下都有一个表达式,则它相当于以下 match 语句。请注意,与 switch 语句不同,我们可以选择返回一个变量(在此代码中,我将结果存储在 $result 中)。

$test = 0.05;
$result = match (true) {
    $test < 0.1 => "I'm less than 0.1",
    $test < 0.01 => "I'm less than 0.01",
    default => "default",
};

var_dump($result);

Match 语句只允许您在每个条件后面有一个表达式。您可以通过调用函数来解决此限制。

function tinyCase(){}
function veryTinyCase(){}
function defaultCase(){}

$test = 0.01;
match (true) {
    $test < 0.1 => tinyCase(),
    $test < 0.01 => veryTinyCase(),
    default => defaultCase(),
};

作为参考,如果您只想检查相等性,可以执行以下操作:

$result = match ($test) { // This example shows doing something other than match(true)
    0.1 => "I'm equal to 0.1",
    0.01 => "I'm equal to 0.01",
    default => "default",
};

Match 语句确实与 switch 语句有一些关键区别,您需要注意:

  • 我的最后一个示例将使用严格的相等性检查 ===< /code> 而不是松散的 ==
  • 如果未提供默认情况,则在没有匹配项时会引发 UnhandledMatchError 错误。
  • 如果您忘记添加 break,也不用担心会陷入下一种情况。

There is an additional way you can accomplish this, in PHP 8.0+, by using a match statement.

If you have a single expression within each case, it is equivalent to the following match statement. Note that unlike switch statements, we can choose to return a variable (in this code I am storing the result in $result).

$test = 0.05;
$result = match (true) {
    $test < 0.1 => "I'm less than 0.1",
    $test < 0.01 => "I'm less than 0.01",
    default => "default",
};

var_dump($result);

Match statements only allow you to have a single expression after each condition. You can work around this limitation by calling a function.

function tinyCase(){}
function veryTinyCase(){}
function defaultCase(){}

$test = 0.01;
match (true) {
    $test < 0.1 => tinyCase(),
    $test < 0.01 => veryTinyCase(),
    default => defaultCase(),
};

And for reference, if you just want to check for equality you can do:

$result = match ($test) { // This example shows doing something other than match(true)
    0.1 => "I'm equal to 0.1",
    0.01 => "I'm equal to 0.01",
    default => "default",
};

Match statements do have some key differences from switch statements that you need to watch out for:

  • My last example will use a strict equality check === instead of a loose one ==.
  • If a default case is not provided, an UnhandledMatchError error is thrown when nothing matches.
  • And there is no worrying about falling through to the next case if you forget to add break.
我的影子我的梦 2024-12-17 17:27:09

带条件的 switch 语句

switch(true)
{
    case ($car == "Audi" || $car == "Mercedes"):
        echo "German cars are amazing";
        break;
    case ($car == "Jaguar"):
        echo "Jaguar is the best";
        break;
    default:
        echo "$car is Ok";
}

Switch statement with conditions

switch(true)
{
    case ($car == "Audi" || $car == "Mercedes"):
        echo "German cars are amazing";
        break;
    case ($car == "Jaguar"):
        echo "Jaguar is the best";
        break;
    default:
        echo "$car is Ok";
}
檐上三寸雪 2024-12-17 17:27:09

PHP 支持 switch 语句。这就是你想要的吗?

PHP supports switch statements. Is that what you wanted?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文