n3p3 Posted June 25, 2009 Share Posted June 25, 2009 how can i rewrite the code below in a more proffessional way. I mean avoiding repetation, using ternary operator in one line or at least two. if (($lastNotified) < strtotime($timeAdded) { if ($i == $count) { echo '<li class="unread last">'.$row['message'].'</li>'; } else { echo '<li class="unread">'.$row['message'].'</li>'; } } else { if ($i == $count) { echo '<li class="last">'.$row['message'].'</li>'; } else { echo '<li>'.$row['message'].'</li>'; } } Quote Link to comment https://forums.phpfreaks.com/topic/163595-better-coding/ Share on other sites More sharing options...
RussellReal Posted June 25, 2009 Share Posted June 25, 2009 otherwise your obvious if statement tragedy it looks alright here is the right if statement if ($lastNotified < strtotime($timeAdded)) { Quote Link to comment https://forums.phpfreaks.com/topic/163595-better-coding/#findComment-863199 Share on other sites More sharing options...
n3p3 Posted June 25, 2009 Author Share Posted June 25, 2009 Sorry, my mistake that I forget the last parentheses. actually what I want to do is to combine if blocks. example; $class = ($lastNotified < strtotime($timeAdded)) ?'undread':''; $class .= ($i == $count)?' last':''; echo '<li'.(!empty($class))?' class="$class"':''.'>'.$row['message'].'</li>'; but, since I've been working with more than one class I couldn't make it work. any suggestions? thank you Quote Link to comment https://forums.phpfreaks.com/topic/163595-better-coding/#findComment-863203 Share on other sites More sharing options...
Adam Posted June 25, 2009 Share Posted June 25, 2009 I think this is what you mean: if (($lastNotified) < strtotime($timeAdded) { echo ($i == $count) ? '<li class="unread last">'.$row['message'].'</li>' : '<li class="unread">'.$row['message'].'</li>'; } else { echo ($i == $count) ? '<li class="last">'.$row['message'].'</li>' : '<li>'.$row['message'].'</li>'; } I've never used a ternary operator with echo before, but should work! Personally though, for easier reading and future development I prefer to use ternary operators as little as possible. Quote Link to comment https://forums.phpfreaks.com/topic/163595-better-coding/#findComment-863215 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.