Search code examples
phpternary

Two if statements using ternary condition


The title seems confusing but this is my first time using ternary conditions. I've read that ternary is meant to be used to make an inline if/else statement. Using no else is not possible. Is it true?

I want to change this with ternary condition for practice

if (isset($_SESSION['group']
{
if ($_SESSION['item'] == 'A')
{
echo "Right!";
}
}

It has two if statements only. The second if is nested with the other. I've also read that to make a no else possible for ternary, it just have to be set to null or empty string.


Solution

  • It's a bad example because you can use an AND-operator on the nested if:

    $result = isset($_SESSION['group'] && $_SESSION['item'] == 'A' ? true : false;
    

    Of course you can nest ternary operator, too:

    $result = isset($_SESSION['group'] ? ( $_SESSION['item'] == 'A' ? true : false ) : false;
    

    with echo

    echo  isset($_SESSION['group'] ? ( $_SESSION['item'] == 'A' ? "Right!" : "false" ) : "false";