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.

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Sarah
  • 39
  • 1
  • 8
  • 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? – Andreas Dec 07 '18 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. – Sarah Dec 07 '18 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 – brombeer Dec 07 '18 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... – Andreas Dec 07 '18 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. – Sarah Dec 07 '18 at 11:09
  • @kerbholz $openMon = ""; is the right one. openMon was a typing error. – Sarah Dec 07 '18 at 11:11

1 Answers1

-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.

Viktor
  • 819
  • 1
  • 12
  • 26