php shorthand issue
I have this:
$color = 开发者_C百科$status == 1 || $status == 2 ? 'read' : 'unread' || $status == 3 ? 'delete' : 'unread';
However it's wrong. If the $status
isn't 3--it still returns 'delete'
What is wrong? Should I use a else if
instead of shorthand for this?
Thanks.
What are you trying to get for your result? I'm assuming you want:
- read
- unread
- delete
unread
$color = ($status == 1) ? 'read' : ($status == 3) ? 'delete' : 'unread'
(which is, for some reason, not showing my line breaks)
For readability, however, I'd use either if/else
or switch
:
switch ($status) {
case 1: $color = 'read'; break;
case 3: $color = 'delete'; break;
default: $color = 'unread';
}
Generally, I don't use the '?:' form unless I will gain a HUGE improvement; usually, more readable is better.
1) || not 100% equal to OR such as && not 100% equal to AND
2) Use brackets
P.S.: yes, use "if .. else" - it will increase code readability.
I would say not to do this as shorthand - longhand will be easier to read, both for you in three days time when you've forgotten what you were doing, or when someone else comes along.
The ternary operator has a wacky binding.
And you could be using a map instead:
$map = array(0=>"unread", 1=>"unread", 2=>"read", 3=>"delete");
$color = $map[ min(3,$status) ]; // min is actually the max value here
Fixed with parenthesis thanks Chvanikoff.
$color = ($status == 1 || $status == 2) ? 'read' : ('unread' || $status == 3 ? 'delete' : '');
精彩评论