
| Using in-line If's (Ternary) |
|
|
|
|
Have you ever wanted to change something in your output in the middle but decided it wasn't worth the 3 extra lines if code in a if statement? Then today's tip is just for you. In-line if or ternary statement can help reduce your code size and make thing more readable. Here is an example code that I have used when writing a results page for search queries in my database: echo $start . " of " . $limit . " of " . $total . " record"; As you can see this will work fine but we have added 3 extra lines of code to make it work. Here is the same code but uses the ternary condition to tighten up the code: echo $start . " of " . $limit . " of " . $total . " record" . ( $limit > 1 ? "s" : "" ) . " found in search."; As you can see this is cleaner and easier to read with the exception of the in-line if. But the more you use these the easier it will be to read. Another good use for in-line ifs is in changing the color of a table row. Here is a example of using integer division and using the remainder to switch between the two colors: $ii=0; We have introduced quite a few new tricks in this code excerpt. The percent sign returns the remainder of the division that takes place. Since we are dividing the value by two our remainder will always be 0 or 1 making the if evaluation either true or false. The other one is the common self increment by one $ii++ every time this runs $ii will get 1 added to its value after the value is used. The last important part of this statement is the else part of the if question. We now will return the light grey when the remainder is 1 and white when the remainder is 0. There are many places you can use this technique so I challenge you to try these out in your next code project. |