Search code examples
phpif-statementvar

PHP if first var is empty use second one


I have a little question if it is possible to check with a variable if one of two variables are not empty and to use their value? Like this:

$var1 = "";
$var2 = "123";
$varifnotempy= $var1 || $var2;
    
echo $varifnotempy;

Here I want not 2 because it give me which one is not empty, but I want that it returns me 123 and if $var1 is not null then to use the value of $var1

I know that I can use if else, but I want to know if it possible to make it by variable.


Solution

  • The traditional way is with the condition (aka "ternary") operator:

    $varifnotempty = $var1 ? $var1 : $var2;
    

    Since 5.3 there's a shorthand:

    $varifnotempty = $var1 ?: $var2;