0
function get_status($data) {
    return ($data->cm_status == 'Y') ? 'Active' :
        ($data->cm_status == 'N') ? 'Inactive' : '-';    
}

I should get Active if $data->cm_status is Y

I should get Inactive if $data->cm_status is N

I should get - if $data->cm_status is anything else

But actually in all case I am getting Inactive

What is the mistake I am doing?

references to your answers appreciated

Sohel Ahmed Mesaniya
  • 3,344
  • 1
  • 23
  • 29
  • Always wrap each deeper condtions in `()` `false ? 'foo' : ( true ? 'bar' :'bobby' )`, its the save way – JustOnUnderMillions Apr 10 '17 at 15:02
  • 1
    In my opinion, using nested ternary operators should be avoyded, specially if you care about readability. You will help yourself and other potential developers if you use clearly written if/else/switch/case instead. – M. Eriksson Apr 10 '17 at 15:05

3 Answers3

4

You need to wrap the inner ternary operator in brackets for the results to be produced correctly, like this

function get_status($data) {
    return $data->cm_status == 'Y' ? 'Active' :
        ($data->cm_status == 'N' ? 'Inactive' : '-');
}

A more readable approach could be to use a switch instead, using nested ternary operators could easily confuse and cause more chaos than it solves. A switch would look like this

function get_status($data) {
    switch ($data->cm_status) {
        case "Y":
            return 'Active';
        case "N":
            return 'Inactive';
        default:
            return '-';
    }
}

This also assumes that the input would always be upper-case, you could add additional code to compare regardless if its upper or lowercase.

Qirel
  • 25,449
  • 7
  • 45
  • 62
0

In case of nested ternary operator the composite one should be inside a couple of brackets. So try this;

function get_status($data) {
    return ($data->cm_status == 'Y') ? 'Active' :(($data->cm_status == 'N') ? 'Inactive' : '-')
}

Notice the "()" in second ternary conditional operator.

KOUSIK MANDAL
  • 2,002
  • 1
  • 21
  • 46
0

Use this:

function get_status($data) {
    return ($data->cm_status == 'Y') ? 'Active' :
        (($data->cm_status == 'N') ? 'Inactive' : '-');    
}
modsfabio
  • 1,097
  • 1
  • 13
  • 29