1

I want to use ternary operator for if-elseif-else. But it is not working for me.

Kindly check the code below:

$openMon = "00:01";  // The below Line Returns Time
$openMon = "00:00";  // The below Line Returns Close

<td><?=(($openMon == '00:00')?'Close':date("g:i a", strtotime($openMon)));?></td>

The above line working perfectly because it returns True or false.

But when $openMon blank it returns 1am. I want when $openMon blank it returns "-"

I want Three Things in one line like:

$openMon = "";        // This is I want in ternary operator with above two conditions

if($openMon == "" ){
    $openMon ="-";
}

I tried:

<td><?=isset((openMon == "")?'-':(($openMon == '00:00')?'Close':date("g:i a", strtotime($openMon)));?></td>

This is not working for me.

Basically I want in ternary operator:

if($openMon == ''){
    $openMon = "-";
}else{
    if($openMon == '00:00'){
        $openMon = "Close";
    }else{
        $openMon = date("g:i a", strtotime($openMon)));
    }
}

Any Idea or suggestions would be helpful.

6
  • 1
    Ternary... But why do you want a messy ternary when you have an if else that does the same thing in a cleaner and easier to read way? Commented Dec 7, 2018 at 11:05
  • @ Andreas Thank you for the response. I am learning the code so I want to learn how to use these things in a single line. Commented Dec 7, 2018 at 11:06
  • isset((openMon == "") Does that work in your if loop? (Missing a $). Also don't "ask" if openMon == "" is set. Ask if $openMon is set. Or if $openMon == "". You're doing both Commented Dec 7, 2018 at 11:07
  • 1
    Single line is a messy way to code and you will regret it when you need to debug or change something. I strongly advice you to not use ternary if it's more than two conditions. And me personally don't ever use it unless... well I don't know how to finnsih that... Commented Dec 7, 2018 at 11:08
  • @ kerbholz thank you for the response. My if-else working fine but I want to use in turnary operator. If-elseif-else. Commented Dec 7, 2018 at 11:09

1 Answer 1

-1

You can use nested ternary operator. Same question was here.

Your code will be like this:

$openMon = !$openMon ? "-" : ($openMon == '00:00' ? "Close" : date("g:i a", strtotime($openMon)))

Your can test this code snippet here.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the reply. You are a great coder. I wanted to learn and you taught me. Thank You.
Have a nice coding! Best regards.)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.