如果为true,则在条件内分配变量 [英] Assign variable within condition if true

查看:82
本文介绍了如果为true,则在条件内分配变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道你可以在这样的条件下分配一个变量:

I know you can assign a variable in a condition like this:

if($ var = $ foo)

但是我不需要在条件本身做任何事情,所以我经常留下空括号。我可以简单地指定 $ var 如果 $ foo true 以某种其他方式而不需要在以后做其他事情?

However I don't need to do anything in the condition itself, so I'm often left with empty brackets. Can I simply assign $var if $foo is true in some other way without needing to do something else later?

我也可以将 $ var 分配给 $ foo 如果 $ foo true 但是如果 $ foo false 做别的事情?喜欢:

Also can I assign $var to $foo if $foo is true but if $foo is false do something else? Like:

if ($var = !$foo) {
    if ($var = !$bar) {
        //Etc...
    }
}

基本上我希望有更多的后备/默认值。

Basically I want to have more fallbacks/defaults.

推荐答案

@ chandresh_cool的建议是正确的,但允许多个可能性/后备,你必须嵌套三元表达式:

@chandresh_cool's suggestion is right but to allow multiple possiblities / fallbacks you would have to nest the ternary expressions:

$var = ($foo == true) ? $foo: 
       ($bar == true) ? $bar: 
       ($fuzz == true) ? $fuzz:
       $default;

注意:前3行以冒号而非分号结束。

Note: the first 3 lines end in colons not semi-colons.

然而,更简单的解决方案是执行以下操作:

However a simpler solution is to do the following:

$var = ($foo||$bar||$fuzz...);

这篇关于如果为true,则在条件内分配变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆