Stacking the Ternary Operator in PHP
TLDR;
$grade =
($score >= 90 ? 'A' : null) ??
($score >= 75 ? 'B' : null) ??
($score >= 65 ? 'C' : null) ??
($score >= 55 ? 'D' : null) ??
'F';
In PHP the ternary operator is left-associative and therefore behaves entirely incorrectly:
As a solution, you could use parentheses, but this quickly becomes messy
$grade = ($score >= 90 ? 'A' : ($score >= 75 ? 'B' : ($score >= 65 ? 'C' : ($score >= 55 ? 'D' : 'F') ) ) );
I prefer to have a single condition per line and not have to worry about the parenthesis.
As a workaround, we can use the Null Coalescing (??
) operator, given that the value that is selected will never be null
.
$grade =
($score >= 90 ? 'A' : null) ??
($score >= 75 ? 'B' : null) ??
($score >= 65 ? 'C' : null) ??
($score >= 55 ? 'D' : null) ??
'F';
In this example, we're just using static strings. However, this also works as expected if we were calling functions for the value, as only the function of the matching condition is called.
CAVEAT; if the value is null
the next condition is tried, rather than returning null
.
Written by Arnold Daniels
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Php operator inline
Authors
Related Tags
#php operator inline
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#