The Problem of Ternary Operators in PHP

How do you think of the ternary operators in PHP? Recently, I’’ve used the code written as below:

echo (1?"Y":0?"N":"");

The code returns “N” but not “Y”. How does it work?

It shoud be like:

echo ((1?"Y":0)?"N":"");

Finally, please follow the advice from PHP docs:

It is recommended that you avoid “stacking” ternary expressions. PHP’s behaviour when using more than one ternary operator within a single statement is non-obvious.

Then you will make better code in PHP.

Reference

1. Mac Taylor, “Stacking Multiple Ternary Operators in PHP, “ stackoverflow [Online]. Available: http://stackoverflow.com/questions/5235632/stacking-multiple-ternary-operators-in-php

This entry was posted in PHP, Programming, 程式設計. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *