Search code examples
phpternary

how to create a php ternary expression containing only if statement


How can I create a php ternary expression containing just if statement without the else part? This is what I tried :

$vn = condition ? expression1 ;

And this is what I'm trying to achieve

if(condition) {
    $vn = expression1;
}

to

$vn = condition ? expression1 ;

Solution

  • You could use the same variable in the else part:

    $vn = condition ? expression1 : $vn ;
    

    Note this creates a notice if $vn was not used before.