| Frames | Modems | Help | Home Page | Chipsets | Search | No Frames |
| Diary Entries | See also Site Info & Diary. | |
| 09 December 2001 | Using the PHP ternary operator... | |
| (See also Chapter 10. Operators) The following fragment of PHP illustrates my recent use of the ternary operator ($mid>0 indicates that an existing /mfc/ is going to be changed, whereas $mid==NULL indicates that a new /mfc/ is going to be added): $q=(($mid)?"UPDATE":"INSERT INTO"). " /mfc/ SET Name='$mName'". ... (($mid)?" WHERE MID=$mid":""); mysql_query($q);The first & last lines both use this operator. The form of the operator is as follows: (True/False Expression) ? t-Expression : f-ExpressionThe above makes clear why it is called a Ternary expression - ternary means 3 parts. If the first expression evaluates to TRUE, then the second expression is returned, else the whole thing evaluates to the third expression. Notice also that in my usage of it I had to wrap each ternary operator in brackets [()] to make them work - a consequence of operator precedence, I'm sure, but I'm more bothered at the moment that it works, not why. As a postscript, when I first tested this live with actual values I forgot to include the last ternary operator - every one of the /mfc/ values was set to the same value. (Sigh) Fortunately, I keep regular backups. |
||