January 1st, 2009
Here are some very useful PHP code shortcuts that I have learned. You may have seen them before or you may not have, but if you didn’t understand them, hopefully you will after reading this article.
The first is the Ternary Operator
<?php $var = (expression) ? 'value if true' : 'value if false'; //The above does the same as the following: if (expression) $var = 'value if true'; else $var = 'value if false'; //Example use: $name = empty($me) ? $you : $me; //sets $name to $me if $me is not empty, or to $you if $me is empty
The next two examples show how to use the “or” and “and” operators (also known as || and &&) as shortcuts
<?php (expression1) or (expression2); //The above does the same as the following: if (!expression1) expression2; //Example use: //I actually found this line of code in the Yii framework defined('YII_DEBUG') or define('YII_DEBUG',true); //Defines the constant YII_DEBUG if it has not been defined already
The above works because in the or operator, the right hand expression is not evaluated unless the left hand expression is evaluated to false (if it evaluates to true, there is no need for the right-hand side to be solved anyways – and PHP tries to be efficient)
The and operator does the exact opposite thing:
<?php (expression1) and (expression2); //The above does the same as the following: if (expression1) expression2; //Example use: ($page > LAST_PAGE) and ($page = LAST_PAGE) //does not allow the page number to be set past the last page
The reason you may want to use these would be to save typing, and to increase readability (in the case of the Ternary Operator anyways, you can argue the other two are less readable). Even if you do not like to use these, it is important to know them in case you ever find yourself reading other people’s code.
Categories: Web Development