Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Ternary conditional operator
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
===PHP=== A simple [[PHP]] implementation is this: <syntaxhighlight lang="php"> $abs = $value >= 0 ? $value : -$value; </syntaxhighlight> Unlike most other programming languages, the conditional operator in [[PHP]] is [[operator associativity|left associative]] rather than right associative. Thus, given a value of '''T''' for '''arg''', the PHP code in the following example would yield the value '''horse''' instead of '''train''' as one might expect:<ref>{{cite web |url=http://eev.ee/blog/2012/04/09/php-a-fractal-of-bad-design/#operators |title=PHP: a fractal of bad design |access-date=2015-10-04 |author=Eevee |date=2012-04-09 }}</ref> <syntaxhighlight lang="php"> <?php $arg = "T"; $vehicle = ( ( $arg == 'B' ) ? 'bus' : ( $arg == 'A' ) ? 'airplane' : ( $arg == 'T' ) ? 'train' : ( $arg == 'C' ) ? 'car' : ( $arg == 'H' ) ? 'horse' : 'feet' ); echo $vehicle; </syntaxhighlight> The reason is that nesting two conditional operators produces an oversized condition with the last two options as its branches: {{code|c1 ? o1 : c2 ? o2 : o3}} is really {{code|((c1 ? o1 : c2) ? o2 : o3)}}. This is acknowledged<ref>{{cite web |url=http://php.net/ternary#example-121 |title=Comparison Operators, Example #3: Non-obvious Ternary Behaviour |publisher=PHP website |access-date=2013-04-26}}</ref> and will probably not change.<ref>{{cite web |url=https://bugs.php.net/bug.php?id=61915 |title=PHP Bug #61915: incorrect associativity of ternary operator |quote=We can't fix this without breaking code |date=2012-05-02 |access-date=2013-04-26 |publisher=PHP website}}</ref> To avoid this, nested parenthesis are needed, as in this example: <syntaxhighlight lang="php"> <?php $arg = "T"; $vehicle = $arg == "B" ? "bus" : ($arg == "A" ? "airplane" : ($arg == "T" ? "train" : ($arg == "C" ? "car" : ($arg == "H" ? "horse" : "feet")))); echo $vehicle; </syntaxhighlight> This will produce the result of '''train''' being printed to the output, analogous to a right associative conditional operator.
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)