Monday, 20 August 2012

Shortcut the else in PHP

Shortcut the else
It should be noted that tips 3 and 4 both might make the code slightly less readable. The emphasis for these tips is on speed and performance. If you’d rather not sacrifice readability, then you might want to skip them.
Anything that can be done to make the code simpler and smaller is usually a good practice. One such tip is to take the middleman out of else statements 6, so to speak. Christian Montoya has an excellent example 7 of conserving characters with shorter else statements.
Usual else statement:
1if( this condition )
2{
3$x = 5;
4}
5else
6{
7$x = 10;
8}
If the $x is going to be 10 by default, just start with 10. No need to bother typing the else at all.
1$x = 10;
2if( this condition )
3{
4$x = 5;
5}
While it may not seem like a huge difference in the space saved in the code, if there are a lot of else statements in your programming, it will definitely add up.

No comments:

Post a Comment