Search code examples
ternary

Does ternary operator can only do one kind of condition?


ternary make code concise and readable, I'm curious about how to change the following if condition to ternary operator:

var1 = if(true){'a'};

I try the following

var1 = true? 'a': ;

since it require nothing to do with false condition, I leave blank after :, but apparently it gives me a error.

Is there a way to do this?

--------update---------

The intention of using the above example is that I want to simplify the problem, however it made everyone more confuse, so I post my original code:

if($_SERVER['REQUEST_METHOD'] == 'GET'){ $sub_count = 0; }

$sub_count = $_SERVER['REQUEST_METHOD'] == 'GET'? 0 : ;

how to change the if condition to ternary ?


Solution

  • $sub_count = null;
    $sub_count = $_SERVER['REQUEST_METHOD'] == 'GET'? 0 : null;
    
    // To check:
    if(!isset($sub_count))
    {
       // Do something because $_SERVER['REQUEST_METHOD'] != 'GET'
    } else {
        if($sub_count===0)
        {
            // REQUEST METHOD IS GET
        }
    }