PHP - $ variable = value1 or value2

$val1 = false;
$val2 = 10;

$variable = $val1 || $val2;

the above code does $variable = true.

Is there any statement in PHP that will make a $variablevalue $val2if $val1false? I thought I would ||do this, but only returns true if either of the values ​​is true or false if both are false ...

+3
source share
3 answers

Ternary operator

$variable = ($val1) ? $val1 : $val2;

or (in PHP 5.3+)

$variable = ($val1) ?: $val2;
+5
source

The operator ||does a boolean or, so you return only true or false.

You might want to use the PHP three-dimensional operator :

$variable = $val1? "default value" : $val2;
+3
source

:

$variable = $value1  or  $variable = "value2";

or , =. , . - - ?: PHP < 5.3.

+2

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


All Articles