Assign a variable to condition if true

I know that you can assign a variable in this state:

if ($var = $foo)

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

You can also assign $var to $foo if $foo is true , but if $foo is false do something else? How:

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

Basically, I want to have more backups / defaults.

+7
source share
4 answers
Sentence

@chandresh_cool is correct, but to allow several features / backups, you would need to lay out ternary expressions:

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

Note: the first 3 lines end with colons, not half-columns.

However, a simpler solution is the following:

 $var = ($foo||$bar||$fuzz...); 
+9
source

Although this is a very old post. Spare logic for falsification values ​​can be encoded as follows.

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

In this case, when $foo is a falsified value (e.g. false, empty string, etc.), it returns to $bar , otherwise $foo . If the bar is a falsified value, it returns to the default line.

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 default text, because empty strings and null are considered "false" values.

[Update]

In php 7 you can use the new operator of union of zeros: ?? , which also checks if a variable exists using isset (). This is useful when you use a key in an array.

Example:

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

Prior to php 7, this would give an Undefined index: foo notification. But with a null union operator, this notification will not appear.

+5
source

Instead, you can use the three-dimensional operator as follows

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

You can assign these values:

 $var = $foo; 

Installing them in an if statement is also possible, PHP will evaluate the resulting $ var that you just assigned.

I really don't ask a question, but you can do something like this:

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

Source: https://habr.com/ru/post/945127/


All Articles