2015年3月19日 星期四

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

沒有留言:

張貼留言