Here are a couple more uses of ternary operators, ranging from simple to advanced: /* another basic usage */ Use enough parenthesis to keep your code organized, but not so many that you create "code soup.".If you aren't experienced with using ternary operators, write your code using if/else first, then translate the code into ?'s and :'s.PHP's behaviour when using more than one ternary operator within a single statement is non-obvious." "Is is recommended that you avoid "stacking" ternary expressions. PHP.net recommends avoiding stacking ternary operators.If you work in a team setting, make sure the other programmers understand the code. Don't go more levels deep than what you feel comfortable with maintaining.Here are a few tips for when using "?:" logic: You can do your if/else logic inline with output instead of breaking your output building for if/else statements.Makes coding simple if/else logic quicker.There are some valuable advantages to using this type of logic: $var_is_greater_than_two = ($var > 2 ? true : false) // returns true What Are The Advantages of Ternary Logic? Ternary operator logic is the process of using "(condition) ? (true return value) : (false return value)" statements to shorten your if/else structures. If/Else statements aren't optimal (or necessary) in all situations. I preach a lot about using shorthand CSS and using MooTools to make JavaScript relatively shorthand, so I look towards PHP to do the same. If / Else statements are great but they can be too long. If / Else statements are easy to code and global to all languages. An essential part of programming is evaluating conditions using if/else and switch/case statements.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |