Jared Jared - 1 month ago 12
PHP Question

Assign variable within condition if true

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.

Answer

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