Assign variable within condition if true

吃可爱长大的小学妹 提交于 2019-12-22 05:06:02

问题


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

if ($var = $foo)

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?

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.


回答1:


@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;

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

However a simpler solution is to do the following:

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



回答2:


Although this is a very old post. Fallback logic on falsify values can be coded like this.

$var = $foo ?: $bar ?: "default";

In this case when $foo is a falsified value (like false, empty string, etc.) it will fall back to $bar otherwise it uses $foo. If bar is a falsified value, it will fallback to the string default.

Keep in mind, that this works with falsified values, and not only true.

example:

$foo = "";
$bar = null;
$var = $foo ?: $bar ?: "default";  

$var will contain the text default because empty strings and null are considered "false" values.

[update]

In php 7 you can use the new null coalescing operator: ??, which also checks if the variable exists with isset(). This is usefull for when you are using a key in an array.

Example:

$array = [];
$bar = null;
$var = $array['foo'] ?? $bar ?? "default";

Before php 7 this would have given an Undefined index: foo notice. But with the null coalescing operator, that notice won't come up.




回答3:


Instead you can Use ternary operator like this

$var = ($foo == true)?$foo:"put here what you want";



回答4:


You can assign values like this:

$var = $foo;

Setting them within an if statement is also possible, PHP will evaluate the resulting $var which you just assigned.

I dont really get your question, but you could do something like this:

if(!($var = $foo)){
   //something else.
}


来源:https://stackoverflow.com/questions/16581174/assign-variable-within-condition-if-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!