仅具有 true 语句的条件运算符

发布于 2024-07-28 17:10:06 字数 430 浏览 8 评论 0原文

我想将变量设置为一个值,但前提是条件为真。
而不是执行以下操作:

if($myarray["foo"]==$bar){  
    $variablename=$myarray["foo"];  
}  

如果变量名称很长,或者可能涉及数组,那么这最终可能会很长,而我想要做的事情很简单 - 如果条件为真则设置一个值。

我想使用条件运算符,如下所示:

$variablename=($myarray["foo"]=="bar")? $myarray["foo"]......

但这会失败,因为如果语句为 false,我根本不希望设置变量。

基本上,我想做的就是使第一个示例更短。 也许条件运算符不是这样的......

有人有什么建议吗?

I want to set a variable to a value, but only if a condition is true.
Instead of doing the following:

if($myarray["foo"]==$bar){  
    $variablename=$myarray["foo"];  
}  

This can end up being quite long if the variable names are long, or perhaps it involves arrays, when it's quite simple what I want to do — set a value if a condition is true.

I would like to use the conditional operator, something like this:

$variablename=($myarray["foo"]=="bar")? $myarray["foo"]......

But this fails because I don't want the variable to be set at all if the statement is false.

Basically, what I'm trying to do is make the first example shorter. Perhaps the conditional operator is not the way though...

Does anyone have any suggestions?

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

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

发布评论

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

评论(2

挽容 2024-08-04 17:18:36

IMO,缩短代码示例的最佳方法是:

if($myarray["foo"] == $bar)
    $variablename = $myarray["foo"];

仅供参考,您所询问的运算符的名称不是“三元运算符”,而是 条件运算符

既然你问了,你实际上可以使用条件运算符来完成你所要求的事情的一种方法是:

$myarray['foo'] == $bar ? $variablename = $myarray['foo'] : null;

但这有点可怕且难以维护。

IMO, the best way to make your code sample shorter is:

if($myarray["foo"] == $bar)
    $variablename = $myarray["foo"];

FYI, the name of the operator you're asking about isn't "the ternary operator", it's the conditional operator.

Since you ask, a way you could actually use the conditional operator to do what you're asking is:

$myarray['foo'] == $bar ? $variablename = $myarray['foo'] : null;

but that's somewhat horrifically ugly and very unmaintainable.

酒几许 2024-08-04 17:16:09

它不会比以下内容短得多:

if($condition) $var = $value;

It doesn't get much shorter than:

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